C# 简单实现WebSocket

简单实现WebSocket

  • 服务器端
    • 1、S端导入SuperSocket包
    • 2、S端实现WebSocket WinForm
  • 网页端
    • 3、B端实现WebSocket

服务器端

1、S端导入SuperSocket包

NuGet包导入

引用包 包内容
log4net SuperSocket内必须包含的打log文件
SuperSocket SuperSocket必要包
SuperSocket.Engine SuperSocket必要包
SuperSocket.WebSocket WebSocket需要用到的包

2、S端实现WebSocket WinForm

与SuperSocket的使用方法一样

//初始化WebSocket
private void StartServer(int port)
{
    WebSocketServer Server = new WebSocketServer();
    Server.NewMessageReceived += Server_NewMessageReceived; ;//当有信息传入时
    Server.NewSessionConnected += Server_NewSessionConnected; ;//当有用户连入时
    Server.SessionClosed += Server_SessionClosed; ;//当有用户退出时
    Server.NewDataReceived += Server_NewDataReceived; ;//当有数据传入时
    Server.Setup(11897)//绑定端口
    Server.Start();//启动服务
}

//WebSocket可以接收string类型数据,也可以接收byte[]类型数据
private void Server_NewMessageReceived(WebSocketSession session, string value)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("From ").Append(session.RemoteEndPoint.ToString()).Append(": \r\n")
        .Append(value).Append("\r\n\r\n");
    BeginInvoke(new Action(() => { textBox1.AppendText(sb.ToString()); }));
}
private void Server_NewDataReceived(WebSocketSession session, byte[] value)
{

}

网页端

3、B端实现WebSocket

新建一个html网页,实现发送与接收string功能


<html>
<head>
	<title>WebSocketClienttitle>
head>
<body>
<script>

	var btnSend    ;
	var status     ;
	var receiveTxt ;
	var sendTxt    ;
	var wsObj ;

   window.onload = function(){
	 btnSend = document.getElementById("btnSend");
	 status = document.getElementById("status");
	 receiveTxt = document.getElementById("receive");
	 sendTxt = document.getElementById("send");

    wsObj = new WebSocket("ws://127.0.0.1:11889");   //建立连接
    wsObj.onopen = function(){  //发送请求
    	var status = document.getElementById("status");
        status.innerHTML = "连接状态: 已连接";
        status.style.color = "green";
    };
    wsObj.onmessage = function(ev){  //获取后端响应
        receiveTxt.value = receiveTxt.value + "\r\n\r\n" + ev.data; 
    };
    wsObj.onclose = function(ev){
        //alert("close");
    };
    wsObj.onerror = function(ev){
       //alert("error");
    };

   }


    function snedMessage() {
    	var str = sendTxt.value;
    	wsObj.send(str);
    }
script>

<div>
	<label id="status" style="color: rgb(255,0,0)">连接状态: 未连接label> 
div>

<div>
	<p>接收p>
	<textarea  name="" id="receive" style="width: 300px;height: 300px">textarea>
div>
<div>
	<p>发送区p>
	<input type="text" name="" id="send" style="width:300px" />
	<br/>
	<br/>
	<input type="button" id="btnSend" value="发送" 
	       style="width :150px;height: 30px"
	       onclick="snedMessage()" 
	/>
div>
body>
html>

C# 简单实现WebSocket_第1张图片

你可能感兴趣的:(WebSocket)