websocket-sharp使用详解及其调用原理

参考官方样例修改,简单实现以下实现两端消息发送。

Client端代码,直接发起连接,连接建立成功后发送初始消息,之后根据键入发送消息。

using System;
using System.Threading;
using WebSocketSharp;

namespace Example
{
  public class Program
  {
    public static void Main (string[] args)
    {
      
      using (var ws = new WebSocket ("ws://127.0.0.1:4649/MyChat"))
      {
        ws.OnOpen += (sender, e) => ws.Send ("Hi, there!");
        ws.Connect ();
        Console.WriteLine ("\nType 'exit' to exit.\n");
        while (true) {
          Thread.Sleep (1000);
          Console.Write ("> ");
          var msg = Console.ReadLine ();
          if (msg == "exit")
            break; 
          // Send a text message.
          ws.Send (msg);
        }
      }
    }
  }
}

Server端代码

这里采用 HttpServer模式,该类不单可以提供正常的websocket服务,还可以作为Http服务使用。

using System;
using System.Configuration;
using System.Text;
using WebSocketSharp;
using WebSocketSharp.Net;
using WebSocketSharp.Server;

namespace Example3
{
    public class MyChat : WebSocketBehavior
    {
        private string _name;

        public MyChat(string name)
        {
            _name = name;
        }

        pro

你可能感兴趣的:(websocket,.net,c#)