c# WebSocket通讯

一、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)); 
                    }
                };
            });
        }
        /// <summary>
        /// 按字节发送
        /// </summary>
        /// <param name="vlue"></param>
        public void Send(byte[] vlue)
        {
            foreach (var socket in allSockets.ToList())
            {
                socket.Send(vlue);
            }
        }
        /// <summary>
        /// 按字符串发送
        /// </summary>
        /// <param name="vlue"></param>
        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);
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值