相关文章推荐
鼻子大的生姜  ·  spring4.0之九:websocket简 ...·  3 月前    · 
酒量小的墨镜  ·  Spring Framework 4.0 ...·  3 月前    · 
霸气的麦片  ·  20. WebSocket Support·  1 月前    · 
魁梧的黑框眼镜  ·  33. WebSockets Support·  1 月前    · 
玩足球的烈马  ·  实战 | spring boot 集成 ...·  1 月前    · 
另类的开水瓶  ·  ODataConventionModelBu ...·  2 年前    · 
急躁的伏特加  ·  Open3d之点云可视化_可视化点云open ...·  2 年前    · 
重感情的大熊猫  ·  ClientScriptManager.Re ...·  2 年前    · 
狂野的投影仪  ·  mysql replace 多个字段 ...·  2 年前    · 
刚失恋的烤面包  ·  go 计算map 差集、并集、交集 - ...·  2 年前    · 
Code  ›  使用websocket-sharp来创建c#版本的websocket服务开发者社区
websocket
https://cloud.tencent.com/developer/beta/article/1057777?areaSource=106005.13
一直单身的抽屉
2 年前
作者头像
JadePeng
0 篇文章

使用websocket-sharp来创建c#版本的websocket服务

前往专栏
腾讯云
备案 控制台
开发者社区
学习
实践
活动
专区
工具
TVP
文章/答案/技术大牛
写文章
社区首页 > 专栏 > JadePeng的技术博客 > 正文

使用websocket-sharp来创建c#版本的websocket服务

发布 于 2018-03-12 16:19:23
3.1K 0
举报

当前有一个需求,需要网页端调用扫描仪,javascript不具备调用能力,因此需要在机器上提供一个ws服务给前端网页调用扫描仪。而扫描仪有一个c#版本的API,因此需要寻找一个c#的websocket库。

java里有大名鼎鼎的netty,通过搜索,c#可以选择 websocket-sharp 来实现websocket Server。

使用websocket-sharp创建websocket server

using System;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace Example
  public class Laputa : WebSocketBehavior
    protected override void OnMessage (MessageEventArgs e)
      var msg = e.Data == "BALUS"
                ? "I've been balused already..."
                : "I'm not available now.";
      Send (msg);
  public class Program
    public static void Main (string[] args)
      var wssv = new WebSocketServer ("ws://dragonsnest.far");
      wssv.AddWebSocketService<Laputa> ("/Laputa");
      wssv.Start ();
      Console.ReadKey (true);
      wssv.Stop ();
}

Step 1

Required namespace.

using WebSocketSharp.Server;

The WebSocketBehavior and WebSocketServer 两个类需要引用 WebSocketSharp.Server namespace.

Step 2

编写处理类,需要继承 WebSocketBehavior class.

例如,如果你要创建一个echo Service,

using System;
using WebSocketSharp;
using WebSocketSharp.Server;
public class Echo : WebSocketBehavior
  protected override void OnMessage (MessageEventArgs e)
    Send (e.Data);
}

再提供一个 chat service,

using System;
using WebSocketSharp;
using WebSocketSharp.Server;
public class Chat : WebSocketBehavior
  private string _suffix;
  public Chat ()
    : this (null)
  public Chat (string suffix)
    _suffix = suffix ?? String.Empty;
  protected override void OnMessage (MessageEventArgs e)
    Sessions.Broadcast (e.Data + _suffix);
}

可以通过继承 WebSocketBehavior 类来自定义Service.

通过重载 WebSocketBehavior.OnMessage (MessageEventArgs) 方法, 来处理消息

同时你也可以重载 WebSocketBehavior.OnOpen () , WebSocketBehavior.OnError (ErrorEventArgs) , 和 WebSocketBehavior.OnClose (CloseEventArgs) 方法,来处理websocket连接事件。

通过 WebSocketBehavior.Send 方法来给客户端发送消息。

If you would like to get the sessions in the service, you should access the WebSocketBehavior.Sessions property (returns a WebSocketSharp.Server.WebSocketSessionManager ).

The WebSocketBehavior.Sessions.Broadcast method can send data to every client in the service.

Step 3

创建 WebSocketServer 对象.

var wssv = new WebSocketServer (4649);
wssv.AddWebSocketService<Echo> ("/Echo");
wssv.AddWebSocketService<Chat> ("/Chat");
wssv.AddWebSocketService<Chat> ("/ChatWithNyan", () => new Chat (" Nyan!"));

Step 4

启动 WebSocket server.

wssv.Start ();

Step 5

停止 WebSocket server.

wssv.Stop (code, reason);

测试Demo

目的 :对外提供一个websocket服务,让网页端的js可以调用扫描仪

服务端代码

 class Program
        static void Main(string[] args)
            var wssv = new WebSocketServer(10086);
            wssv.AddWebSocketService<ScannerHandler>("/scan");
            wssv.Start();
            if (wssv.IsListening)
                Console.WriteLine("Listening on port {0}, and providing WebSocket services:", wssv.Port);
                foreach (var path in wssv.WebSocketServices.Paths)
                    Console.WriteLine("- {0}", path);
            Console.WriteLine("\nPress Enter key to stop the server...");
            Console.ReadLine();
            wssv.Stop();
    public class ScannerHandler : WebSocketBehavior
        protected override void OnMessage(MessageEventArgs e)
            if(e.Data == "scan")
                ScanResult result = ScanerHelper.Scan("D:\\test.jpg");
                if (result.Success)
                    Console.WriteLine("scan success");
                    Send("scan success");
                    Send("scan eror");
    }

前端代码

javascript代码

    var ws;
    function initWS() {
        ws = new WebSocket("ws://127.0.0.1:10086/scan");
        ws.onopen = function () {
            console.log("Openened connection to websocket");
        ws.onclose = function () {
            console.log("Close connection to websocket");
            // 断线重连
            initWS();
        ws.onmessage = function (e) {
            alert(e.data)
 
推荐文章
鼻子大的生姜  ·  spring4.0之九:websocket简单应用 - duanxz
3 月前
酒量小的墨镜  ·  Spring Framework 4.0 M1: WebSocket Support
3 月前
霸气的麦片  ·  20. WebSocket Support
1 月前
魁梧的黑框眼镜  ·  33. WebSockets Support
1 月前
玩足球的烈马  ·  实战 | spring boot 集成 websocket 的四种方式开发者社区
1 月前
另类的开水瓶  ·  ODataConventionModelBuilder.Ignore 方法 (Microsoft.AspNet.OData.Builder) | Microsoft Learn
2 年前
急躁的伏特加  ·  Open3d之点云可视化_可视化点云open3d_ancy_i_cv的博客-CSDN博客
2 年前
重感情的大熊猫  ·  ClientScriptManager.RegisterForEventValidation Method (System.Web.UI) | Microsoft Learn
2 年前
狂野的投影仪  ·  mysql replace 多个字段 mysql使用replace_mob6454cc7c268c的技术博客_51CTO博客
2 年前
刚失恋的烤面包  ·  go 计算map 差集、并集、交集 - 周伯通之草堂 - 博客园
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号