基于HTML5的WebSocket的实例代码
程序员文章站
2023-12-03 09:32:04
这篇文章主要介绍了基于HTML5的WebSocket的实例代码,需要的朋友可以参考下... 18-08-15...
基于html5的websocket的实例代码
客户端代码:
<html> <head> <script> var socket; if ("websocket" in window) { var ws = new websocket("ws://127.0.0.1:8181"); socket = ws; ws.onopen = function() { console.log('连接成功'); }; ws.onmessage = function(evt) { var received_msg = evt.data; document.getelementbyid("showmes").value+=evt.data+"\n"; }; ws.onclose = function() { alert("断开了连接"); }; } else { alert("浏览器不支持websocket"); } function login(){ var message=document.getelementbyid("name").value+":"+document.getelementbyid("mes").value; socket.send(message); } </script> </head> <body> <textarea rows="3" cols="30" id="showmes" style="width:300px;height:500px;"></textarea> <br/> <label>名称</label> <input type="text" id="name"/> <br/> <label>消息</label> <input type="text" id="mes"/> <button onclick="login();">发送</button> </body> </html>
winform服务端代码:
注:需先引入fleck包
using system; using system.collections.generic; using system.linq; using system.windows.forms; using fleck; namespace socketservice { public partial class form1 : form { public form1() { initializecomponent(); checkforillegalcrossthreadcalls = false; } private void form1_load(object sender, eventargs e) { //保存所有连接 var allsockets = new list<iwebsocketconnection>(); //初始化服务端 var server = new websocketserver("ws://0.0.0.0:8181"); //开始监听 server.start(socket => { //有客户端连接触发 socket.onopen = () => { textbox3.text += socket.connectioninfo.clientipaddress + " 连接 \r\n"; allsockets.add(socket); }; //有客户端断开触发 socket.onclose = () => { textbox3.text += socket.connectioninfo.clientipaddress + " 断开连接 \r\n"; allsockets.remove(socket); }; //接收客户端发送的消息 socket.onmessage = message => { textbox3.text += socket.connectioninfo.clientipaddress + " 发送了消息:" + message + "\r\n"; //发送接收到的消息给所有客户端 allsockets.tolist().foreach(s => s.send(message)); }; }); } } }
总结
以上所述是小编给大家介绍的基于html5的websocket的实例代码,希望对大家有所帮助
下一篇: Html5页面在微信端的分享的实现方法