zoukankan      html  css  js  c++  java
  • WebSocketSharp 创建客户端和服务端

    这里没有对onOpen、onClose、onError做案例,生产环境需要具备。

    1.客户端

    只推送不接收数据

    创建WebSocketClient类

     1 class WebSocketClient
     2     {
     3         WebSocket ws;
     4         string host;
     5         string port;
     6         public WebSocketClient()
     7         {
     8             string[] tcpPoint = XMLHelper.getArrayHost("/host/tcphost");
     9             host = tcpPoint[0];
    10             port = tcpPoint[1];
    11             ws = new WebSocket("ws://" + host + ":" + port);
    12             ws.Connect();
    13         }
    14 
    15         public bool ConnState()
    16         {
    17             if (ws.ReadyState==WebSocketState.Open)
    18             {
    19                 return true;
    20             }
    21             return false;
    22         }
    23 
    24         public void SendData(string json)
    25         {
    26             ws.Send(json);
    27         }
    28 }

    2.服务端

    创建Chat类,接收数据

     1 class Chat:WebSocketBehavior
     2     {
     3         protected override async Task OnMessage(MessageEventArgs e)
     4         {
     5 
     6             StreamReader reader = new StreamReader(e.Data);
     7             string text = reader.ReadToEnd();
     8             try
     9             {
    10                 //业务处理
    11             }
    12             catch (Exception exception)
    13             {
    14                 Console.WriteLine(exception);
    15             }
    16         } 
    17 }           

    Main

     1 class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5             int port=8088;//监听端口号
     6             var wsServer = new WebSocketServer(null, port);
     7             wsServer.AddWebSocketService<Chat>("/");
     8             wsServer.Start();
     9             Console.WriteLine("开启" + port + "端口WebSocket监听...");
    10             
    11             Console.ReadKey(true);
    12             wsServer.Stop();
    13         }
    14     }
  • 相关阅读:
    学习进度——第五周
    构建之法阅读笔记02
    学习进度——第四周
    整型数组——首尾相连
    构建之法阅读笔记01
    二维数组
    学习进度——第三周
    新最大子数组——数量级和数量无限大
    最大子数组求和
    P3388 【模板】割点(割顶)题解 tarjan求割点
  • 原文地址:https://www.cnblogs.com/X-Jonney/p/11376092.html
Copyright © 2011-2022 走看看