c# WebSocket通讯

c# 使用websocket简单案例

  • 一、Websocket是什么?
    • 二、使用步骤
      • 1.服务端
      • 2.客户端代码

一、Websocket是什么?

WebSocket是先通过Http进行一次握手,然后通过(全双工)TCP进行传输数据。话不多直接代码

二、使用步骤

1.服务端

Program.cs 代码如下:

using System;
using System.Net.WebSockets;

namespace CommApp
{
    class Program
    {
        public static WebSocket web = new WebSocket();
        static void Main()
        {
            // 启动websocket
            web.WebStart();
            while (true)
            {
                // 从窗体中读取用户输入,然后发送给web
                web.Send(Console.ReadLine());
            }
        }
    }
}

WebSocket.cs 代码如下:

using Fleck;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CommApp
{
    public class WebSocket
    {
        private List<IWebSocketConnection> allSockets = new List<IWebSocketConnection>();
        public void WebStart()
        {
            FleckLog.Level = LogLevel.Debug;
            allSockets = new List<IWebSocketConnection>();
            WebSocketServer server = new WebSocketServer("ws://127.0.0.1:2000/");
            server.Start(socket =>
            {
                socket.OnOpen = () => { allSockets.Add(socket); };
                socket.OnClose = () => { allSockets.Remove(socket); };
                socket.OnMessage = message => {
                    try
                    {
                        Console.WriteLine("接收:" + message);
                    }
                    catch (Exception e)
                    {
                        // 立即反馈异常信息
                        allSockets.ToList().ForEach(s => s.Send("数据错误:" + e.Message)); 
                    }
                };
            });
        }
        /// 
        /// 按字节发送
        /// 
        /// 
        public void Send(byte[] vlue)
        {
            foreach (var socket in allSockets.ToList())
            {
                socket.Send(vlue);
            }
        }
        /// 
        /// 按字符串发送
        /// 
        /// 
        public void Send(string vlue)
        {
            foreach (var socket in allSockets.ToList())
            {
                socket.Send(vlue);
            }
        }
    }
}

2.客户端代码

html代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>websocket client</title>
</head>
<body>
    <table width="50%" height="100%">
        <tr>
            <td height="100">
                <form onsubmit="send();return false;">
                    <table width="100%" height="100%" cellpadding="0" cellspacing="0">
                        <tr>
                        <td>
                            <textarea id="sendText" style="width:100%;height:80px;" />data</textarea><br />
                        </td>
                        <td width="100" align=center>
                            <input type="button" value="发送" onclick="SendText()" style="height:60px;width:60px;"/></td>
                        </tr>
                    </table>
                </form>
            </td>
        </tr>
        <tr>
            <td>
                <textarea id="recvText" style="width:100%;height:100%"></textarea>
            </td>
        </tr>
    </table>
</body>
<script src="socket.js"></script>
</html>

js代码如下:

var input = document.getElementById('sendText');
var recv = document.getElementById('recvText');
var wsImpl = window.WebSocket || window.MozWebSocket;
recv.value += "connecting to server\r\n";
// create a new websocket and connect
window.ws = new wsImpl('ws://127.0.0.1:2000/');
// when data is comming from the server, this metod is called
ws.onmessage = function (evt) {
    recv.value += evt.data + '\r\n';
};
// when the connection is established, this method is called
ws.onopen = function () {
    recv.value += 'connection open\r\n';
};
// when the connection is closed, this method is called
ws.onclose = function () {
    recv.value += 'connection closed\r\n';
}
// 发送消息
function SendText()
{
var input=document.getElementById("sendText").value;
    ws.send(input);
}

你可能感兴趣的:(网络协议,c#,websocket,开发语言,网络协议,网络)