根据HTML5的WebSocket的案例编码

日期:2021-02-27 类型:科技新闻 

关键词:微擎小程序开发,微信小程序下载,如何在微信上做小程序,调查问卷微信小程序,微信抽签小程序

根据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的案例编码,期待对大伙儿有一定的协助,假如大伙儿有任何疑惑请给我留言,网编会立即回应大伙儿的。在此也十分谢谢大伙儿对脚本制作之家网站的适用!