如何在没有 ASP.NET 的情况下使用 System.Net.WebSockets? [英] How to work with System.Net.WebSockets without ASP.NET?

查看:24
本文介绍了如何在没有 ASP.NET 的情况下使用 System.Net.WebSockets?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 .NET 4.5 及更高版本(在 Windows 8.1 上)中使用新的 System.Net.WebSockets 类实现一个简单的聊天服务器.但是,我只找到在 ASP.NET 环境中使用这些类的示例(尤其是这里的示例:http://www.codemag.com/Article/1210051)

I want to implement a simple chat server with the new System.Net.WebSockets classes in .NET 4.5 and later (on Windows 8.1). However, I only find examples making use of those classes in an ASP.NET environment (especially the ones here: http://www.codemag.com/Article/1210051)

我没有这样的服务器,并且希望尽可能原始"地实现 websocket 服务器,但不必重新实现所有的 websocket 协议,因为微软希望在 .NET 4.5 中已经做到了.

I don't have such one, and would like to implement the websocket server as "raw" as possible, but without having to reimplement all the websocket protocol as Microsoft hopefully already did that in .NET 4.5.

我想简单地实例化一个新的 WebSocket 类,就像我对普通 Socket 所做的那样,但构造函数是受保护的.所以我去创建一个继承自它的类,但后来我注意到我必须实现如此多的抽象方法和属性,看起来我正在重写整个逻辑(特别是因为我必须实现诸如 StateSendAsync).

I thought of simply instantiating a new WebSocket class like I'd do with a normal Socket, but the constructor is protected. So I went to create a class inheriting from it, but then I noticed I had to implement so many abstract methods and properties that it looked like I'm rewriting the whole logic (especially because I had to implement things like State or SendAsync).

恐怕 MSDN 文档对我没有帮助.那里的文档处于预发布状态,许多评论只是说待定"或实施时".

I'm afraid that the MSDN documentation didn't help me. The documentation there has a pre-release status and many comments just say "TBD" or "when its implemented".

推荐答案

是.

最简单的方法是使用 HTTPListener.如果您搜索 HTTPListener WebSocket,您会发现很多示例.

The easiest way is to use an HTTPListener. If you search for HTTPListener WebSocket you'll find plenty of examples.

简而言之(伪代码)

HttpListener httpListener = new HttpListener();
httpListener.Prefixes.Add("http://localhost/");
httpListener.Start();

HttpListenerContext context = await httpListener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
    HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
    WebSocket webSocket = webSocketContext.WebSocket;
    while (webSocket.State == WebSocketState.Open)
    {
        await webSocket.SendAsync( ... );
    }
}

需要 .NET 4.5 和 Windows 8 或更高版本.

Requires .NET 4.5 and Windows 8 or later.

这篇关于如何在没有 ASP.NET 的情况下使用 System.Net.WebSockets?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆