本篇文章给大家带来的内容是关于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 sendmes(){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="sendmes();">发送</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));};});}}}
相关推荐:
php+html5基于websocket实现聊天室的方法,html5websocket
利用html5的websocket实现websocket聊天室_html5教程技巧
以上就是html5实现的websocket一个小例子(附代码)的详细内容。