草庐IT

websocket与C# socket相互通信

jsper 2024-01-09 原文
web端代码就是js代码,C#有两种方式:使用第三方库,如Fleck,使用C#原生socket编程实现
 
web端:
<!doctype html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>下发网站上文件到学生机</title>
        <script type="text/javascript">
            function callDesktopReceiveFile(button) {
                var ws = null;
                if (button.innerHTML == '下发') {
                    button.innerHTML = '取消';

                    try {
                        if (ws) ws.close();
                    } catch(e) {
                        console.log(e)
                    }

                    ws = new WebSocket('ws://127.0.0.1:14567');
                    //监听是否连接成功
                    ws.onopen = function () {
                        console.log('ws连接状态[成功]:' + ws.readyState);
                        ws.send("content:receiveFile;url:http://127.0.0.1:5500/2023CQGKMNT.dat;");
                        // ws.close();
                        console.log('发送消息');
                    };

                    // 接听服务器发回的信息并处理展示
                    ws.onmessage = function (e) {
                        console.log('接收到来自服务器的消息:' + e.data);
                        // 如果服务器在业务上主动关闭连接,则此处无需再关闭
                        // if (e.data === 'roger') {
                        //     ws.close();
                        // }
                    };

                    // 监听连接关闭事件
                    ws.onclose = function () {
                        // 监听整个过程中websocket的状态
                        console.log('ws连接状态[关闭]:' + ws.readyState);
                    };

                    // 监听并处理error事件
                    ws.onerror = function (error) {
                        console.log(error);
                    };


                } else if (button.innerHTML == '取消') {
                    try {
                        if (ws) ws.close();
                    } catch(e) {
                        console.log(e)
                    }
                    button.innerHTML = '下发';
                }
            }


        </script>
    </head>
    <body>
        <div>
            <table border="1" cellspacing="0">
                <tr>
                    <th>试卷号</th>
                    <th>试卷名称</th>
                    <th>描述</th>
                    <th>操作</th>
                </tr>
                <tr>
                    <td>JCLX01</td>
                    <td>基础练习一</td>
                    <td>建账、会计期间设置、部门职员设置、银行账户设置、科目设置等</td>
                    <td><button id="btnDownload" onclick="callDesktopReceiveFile(this)">下发</button></td>
                </tr>
                <tr>
                    <td>JCLX02</td>
                    <td>基础练习二</td>
                    <td>建账、会计期间设置、部门职员设置、银行账户设置、科目设置等</td>
                    <td><button id="btnDownload" onclick="callDesktopReceiveFile(this)">下发</button></td>
                </tr>
            </table>
            
        </div>
    </body>
</html>
 
C#端
方式一:使用第三方库Fleck
参考:http://chanpinxue.cn/archives/979.html
 
方式二:使用C#原生socket编程自行实现
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using U8FileTransfer.TcpHelper;
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography;

namespace CodeExperiment
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Thread thread = new Thread(websocketListen);
            thread.IsBackground = true;
            thread.Start();
            
        }

        /// <summary>
        /// 解析客户端数据包,防止乱码
        /// </summary>
        /// <param name="recBytes">服务器接收的数据包</param>
        /// <param name="recByteLength">有效数据长度</param>
        /// <returns></returns>
        private static string AnalyticData(byte[] recBytes, int recByteLength)
        {
            if (recByteLength < 2) { return string.Empty; }
            bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit,1表示最后一帧  
            if (!fin)
            {
                return string.Empty;// 超过一帧暂不处理 
            }
            bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩码  
            if (!mask_flag)
            {
                return string.Empty;// 不包含掩码的暂不处理
            }
            int payload_len = recBytes[1] & 0x7F; // 数据长度  
            byte[] masks = new byte[4];
            byte[] payload_data;
            if (payload_len == 126)
            {
                Array.Copy(recBytes, 4, masks, 0, 4);
                payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]);
                payload_data = new byte[payload_len];
                Array.Copy(recBytes, 8, payload_data, 0, payload_len);
            }
            else if (payload_len == 127)
            {
                Array.Copy(recBytes, 10, masks, 0, 4);
                byte[] uInt64Bytes = new byte[8];
                for (int i = 0; i < 8; i++)
                {
                    uInt64Bytes[i] = recBytes[9 - i];
                }
                UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0);
                payload_data = new byte[len];
                for (UInt64 i = 0; i < len; i++)
                {
                    payload_data[i] = recBytes[i + 14];
                }
            }
            else
            {
                Array.Copy(recBytes, 2, masks, 0, 4);
                payload_data = new byte[payload_len];
                Array.Copy(recBytes, 6, payload_data, 0, payload_len);
            }
            for (var i = 0; i < payload_len; i++)
            {
                payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]);
            }
            return Encoding.UTF8.GetString(payload_data);
        }

        /// <summary>
        /// 打包服务器数据,防止乱码
        /// </summary>
        /// <param name="message">数据</param>
        /// <returns>数据包</returns>
        private static byte[] PackData(string message)
        {
            byte[] contentBytes = null;
            byte[] temp = Encoding.UTF8.GetBytes(message);
            if (temp.Length < 126)
            {
                contentBytes = new byte[temp.Length + 2];
                contentBytes[0] = 0x81;
                contentBytes[1] = (byte)temp.Length;
                Array.Copy(temp, 0, contentBytes, 2, temp.Length);
            }
            else if (temp.Length < 0xFFFF)
            {
                contentBytes = new byte[temp.Length + 4];
                contentBytes[0] = 0x81;
                contentBytes[1] = 126;
                contentBytes[2] = (byte)(temp.Length & 0xFF);
                contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF);
                Array.Copy(temp, 0, contentBytes, 4, temp.Length);
            }
            else
            {
                // 暂不处理超长内容  
            }
            return contentBytes;
        }


        /// <summary>
        /// 客户端消息结构化
        /// message参数格式为多个key:value键值对通过分号拼接组成,示例:
        /// content:download_and_send;file-url:https://www.a.com/a.zip;
        /// 
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private Dictionary<string, string> ProcessRemoteMessage(string message)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (message.Substring(message.Length - 1, 1) == ";")
            {
                message = message.Substring(0, message.Length - 1);
            }
            string[] strs = message.Split(';');
            if (strs.Length > 0)
            {
                Console.WriteLine("- - - - - - - - - - - - - - - - - - -");
                foreach (string s in strs)
                {
                    Console.WriteLine(s);
                    string[] split = s.Split(new char[] { ':' }, 2);
                    Console.WriteLine("[" + split[0] + "][" + split[1] + "]");
                    dic.Add(split[0], split[1]);
                }
                Console.WriteLine("- - - - - - - - - - - - - - - - - - -");
            }
            return dic;
        }

        private void websocketListen()
        {
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EndPoint endPoint = new IPEndPoint(IPAddress.Any, 14567);//监听端口
            server.Bind(endPoint);
            server.Listen(10); // 排队等待连接最大数量10

            // 监听多个客户端连接
            while (true)
            {
                Socket client = server.Accept();
                Console.WriteLine("有客户端连上来了");

                //接收客户端发来的HTTP-Header消息
                byte[] bytes = new byte[1024];
                int len = client.Receive(bytes);
                string strMessage = Encoding.UTF8.GetString(bytes, 0, len);
                Console.WriteLine(strMessage);

                //获取Sec-WebSocket-Key,为握手做准备
                string[] strings = strMessage.Split('\n');
                string strSecWebSocketKey = "";
                foreach (var item in strings)
                {
                    string[] strings1 = item.Split(':');
                    if (strings1[0] == "Sec-WebSocket-Key")
                    {
                        strSecWebSocketKey = strings1[1].Trim();
                    }
                }

                //生成服务端Sec-WebSocket-Accept,迎合客户端的握手请求
                byte[] secKeyBytes = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(strSecWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
                string secKey = Convert.ToBase64String(secKeyBytes);

                // 发送给客户端完成握手(会触发Websocket的open()回调函数),针对websocket必须使用以下header
                string strHeader = "";
                strHeader += "HTTP/1.1 101 Switching Protocols" + Environment.NewLine;
                strHeader += "Upgrade: websocket" + Environment.NewLine;
                strHeader += "Connection: Upgrade" + Environment.NewLine;
                strHeader += "Sec-WebSocket-Accept: " + secKey + Environment.NewLine + Environment.NewLine;
                client.Send(Encoding.UTF8.GetBytes(strHeader));

                string remoteFileUrl = null;
                bool clientClose = false;
                // 循环接收websocket发来的消息实现双方交流
                while (!clientClose)
                {
                    //接收客户端发来的消息
                    byte[] bytes2 = new byte[1024];
                    int len2 = client.Receive(bytes2);
                    string strMessage2 = AnalyticData(bytes2, len2);
                    if (strMessage2.Length > 0)
                    {
                        Console.WriteLine("客户端发来消息:{0}", strMessage2);
                        Dictionary<string, string> messageDic = ProcessRemoteMessage(strMessage2);
                        string content = null;
                        messageDic.TryGetValue("content", out content);
                        Console.WriteLine("message content:" + content);
                        if (content == "receiveFile")
                        {
                            messageDic.TryGetValue("url", out remoteFileUrl);
                            client.Send(PackData("roger"));
                            Console.WriteLine("remoteFileUrl: " + remoteFileUrl);
                            Console.WriteLine("to do invoke download.");
                            // 关闭连接
                            client.Shutdown(SocketShutdown.Both);
                            client.Close();
                            clientClose = true;
                        }
                    }
                    else
                    {
                        Console.WriteLine("客户端关闭了连接");
                        client.Shutdown(SocketShutdown.Both);
                        client.Close();
                    }
                }
            }
        }

    }
}

 

websocket关闭机制
通信双方都可以主动关闭连接,不管谁关闭连接,对方都能收到消息。
client端关闭连接,server端能收到内容长度为0的消息。
server端关闭连接,client端会触发onclose事件。
 

有关websocket与C# socket相互通信的更多相关文章

  1. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  2. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  3. MIMO-OFDM无线通信技术及MATLAB实现(1)无线信道:传播和衰落 - 2

     MIMO技术的优缺点优点通过下面三个增益来总体概括:阵列增益。阵列增益是指由于接收机通过对接收信号的相干合并而活得的平均SNR的提高。在发射机不知道信道信息的情况下,MIMO系统可以获得的阵列增益与接收天线数成正比复用增益。在采用空间复用方案的MIMO系统中,可以获得复用增益,即信道容量成倍增加。信道容量的增加与min(Nt,Nr)成正比分集增益。在采用空间分集方案的MIMO系统中,可以获得分集增益,即可靠性性能的改善。分集增益用独立衰落支路数来描述,即分集指数。在使用了空时编码的MIMO系统中,由于接收天线或发射天线之间的间距较远,可认为它们各自的大尺度衰落是相互独立的,因此分布式MIMO

  4. ruby - Faye WebSocket,关闭处理程序被触发后重新连接到套接字 - 2

    我有一个super简单的脚本,它几乎包含了FayeWebSocketGitHub页面上用于处理关闭连接的内容:ws=Faye::WebSocket::Client.new(url,nil,:headers=>headers)ws.on:opendo|event|p[:open]#sendpingcommand#sendtestcommand#ws.send({command:'test'}.to_json)endws.on:messagedo|event|#hereistheentrypointfordatacomingfromtheserver.pJSON.parse(event.d

  5. C/C++好用的websocket库 - 2

    IntrductionLibwebsocketsisasimple-to-use,MIT-license,pureClibraryprovidingclientandserverforhttp/1,http/2,websockets,MQTTandotherprotocolsinasecurity-minded,lightweight,configurable,scalableandflexibleway.It’seasytobuildandcross-buildviacmakeandissuitablefortasksfromembeddedRTOSthroughmasscloudservi

  6. ruby - 为什么会.is_a?和 .class 给出相互矛盾的结果? - 2

    我有三个属于同一个类的对象。一个是通过Item.new创建的,另外两个是从数据库(Mongoid)中提取的。我将这些对象中的一个/任何一个传递给另一个方法,并通过is_a?检查该方法中的类型:definitialize(item,attrs=nil,options=nil)super(attrs,options)raise'invaliditemobject'unlessitem.is_a?(Item)好吧,这次加薪被击中了。所以我在Rails控制台中检查类、is_a和instance_of。我得到相互矛盾的结果。为什么它们有相同的class但只有其中一个是那个class的instan

  7. ruby-on-rails - Websocket-rails 不适用于 Nginx 和 Unicorn 的生产环境 - 2

    我有带有gemwebsocket-rails0.7的Rails3.2应用程序。在开发机上,一切正常在生产环境中,我使用Nginx/1.6作为代理服务器,Unicorn作为http服务器。Thin用于独立模式(在https://github.com/websocket-rails/websocket-rails/wiki/Standalone-Server-Mode之后)。nginx配置:location/websocket{proxy_passhttp://localhost:3001/websocket;proxy_http_version1.1;proxy_set_headerUp

  8. 1个串口用1根线实现多机半双工通信+开机控制电路 - 2

    功能需求:主机使用一个串口,与两个从机进行双向通信,主机向从机发送数据,从机能够返回数据,由于结构限制,主机与从机之间只有3根线(电源、地、数据线),并且从机上没有设物理的电源开关,需要通过与主机连接的数据线来控制开机,总结如下:1、数据线只有1根2、能够双向通信3、主机能够控制从机开机4、主机可以单独向1个从机发数据,也可以同时向两个从机发送数据根据需求,设计出如下电路:工作原理分析:VCC_24V_IN、GND、LINE_L(LINE_R)三根线接线连接到从机,电源开启电路是从机内部的电源控制。开机的逻辑:*主机先上电,LINE_L因为主机的R1上拉而有高电平,使Q6导通,Q5的G极电压被

  9. WebSocket的那些事(1-概念篇) - 2

    目录一、什么是Websocket二、WebSocket部分header介绍三、HTTPVSWebSocket四、什么时候使用WebSockets五、关于SockJS和STOMP一、什么是Websocket根据RFC6455标准,Websocket协议提供了一种标准化的方式在客户端和服务端之间通过TCP连接建立全双工、双向通信渠道。它是一种不同于HTTP的TCP协议,但是被设计为在HTTP基础上运行。Websocket交互始于HTTP请求,该请求会通过HTTPUpgrade请求头去升级请求,进而切换到Websocket协议。请求报文如下:GET/spring-websocket-portfoli

  10. 已解决socket.timeout : The read operation timed out - 2

    已解决(pip安装模块超时,利用四种国内镜像源完美解决)WARENTING:Retrying(Retry(total=4,connect=None,read=None,redirect=None,status=None))afterconnectionbrokenby‘ConnectTimeoutError(pip._vendor.urllib3.connection.HTTPSConnectionobjectatOx00001D6OE4F4A940>,‘Connectiontopypi.orgtimedout.(connecttimeout=15)’)’':/simple/pip/socke

随机推荐