HTML5 WebSocket实例(一)

来源:互联网 发布:闪电分期go额度淘宝 编辑:程序博客网 时间:2024/04/29 09:52

1.实例1:

HTML

<input type="button" value="打开链接" onclick="openClick();" /><input type="text" id="txt1" /><input type="button" value="发送" id="sendBtn" onclick="sendClick();" /><input type="button" value="关闭" id="closeBtn" onclick="closeClick();" />
JS

var url = 'ws://localhost:55373/upload1.ashx';var ws = null;//打开链接function openClick() {    ws = new WebSocket(url);    ws.onopen = function (e) {        console.log('链接打开');        ws.send('hello ws');    }    ws.onmessage = function (e) {        console.info('接受到数据:' + e.data);    }    ws.onclose = function (e) {        //e  CloseEvent对象        //e.code 关闭代码编号标识        //e.reason 关闭原因        console.info(e);        console.log('链接已经关闭');    }    ws.onerror = function (e) {        console.info(e);        console.log('发生异常:'+e.message);    }}//发送function sendClick() {    var content = document.getElementById('txt1').value;    //如果发送缓冲区没有数据才继续发送    if (ws.bufferedAmount <= 0) {        ws.send(content);    }}//关闭/** 关闭链接说明,在IE浏览器下还会触发 onerror事件*  WebSocket Error: Network Error 12030, 与服务器的连接意外终止*/function closeClick() {    //默认关闭代码 1006    ws.close();    ws = null;    //Uncaught InvalidAccessError: Failed to execute 'close' on 'WebSocket': The code must be either 1000, or between 3000 and 4999. 1006 is neither.    //ws.close(3000,'客户端主动关闭');}
Ashx后台代码处理:

public void ProcessRequest(HttpContext context2){    //得到当前WebSocket请求    HttpContext.Current.AcceptWebSocketRequest(async (context) =>    {        WebSocket socket = context.WebSocket;//Socket        while (true)        {            ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);            CancellationToken token;            WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, token);            if (socket.State == WebSocketState.Open)            {                string userMessage = Encoding.UTF8.GetString(buffer.Array, 0,                        result.Count);                userMessage = "You sent: " + userMessage + " at " +                        DateTime.Now.ToLongTimeString();                buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));                await socket.SendAsync(buffer, WebSocketMessageType.Text,                        true, CancellationToken.None);            }            else { break; }        }    });}
2.实例2:

HTML

<input type="text" id="msg" /><input type="button"  value="发送消息" onclick="sendMsg();" />
JS

var wsServer = 'ws://localhost:55373/upload1.ashx'; //基于.NET4.5服务器地址var websocket = new WebSocket(wsServer); //创建WebSocket对象//websocket.send("hello");//向服务器发送消息 ,在此处发送会抛出异常Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.//alert(websocket.readyState);//查看websocket当前状态websocket.onopen = function (evt) {    //已经建立连接    alert("已经建立连接");};websocket.onclose = function (evt) {    //已经关闭连接    alert("已经关闭连接");};websocket.onmessage = function (evt) {    //收到服务器消息,使用evt.data提取    evt.stopPropagation()    evt.preventDefault()    writeToScreen(evt.data);    //websocket.close();};websocket.onerror = function (evt) {    //产生异常    writeToScreen(evt.message);};function sendMsg() {    if (websocket.readyState == websocket.OPEN) {        msg = document.getElementById("msg").value;        websocket.send(msg);        writeToScreen("发送成功!");    } else {        writeToScreen("链接还没有打开!");    }}function writeToScreen(message) {    var pre = document.createElement("p");    pre.style.wordWrap = "break-word";    pre.innerHTML += message;    document.body.appendChild(pre);}

后台处理同上。

HTML5 WebSocket API简介

demo源代码

1 0