c# websocket服务端
时间: 2023-11-20 12:58:59 浏览: 203
以下是使用C#编写WebSocket服务端的示例代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace WebSocketServerDemo
{
public class MyWebSocketService : WebSocketBehavior
{
protected override void OnMessage(MessageEventArgs e)
{
string receivedMessage = e.Data;
Console.WriteLine("Received message: " + receivedMessage);
// Echo the received message back to the client
Send("Echo: " + receivedMessage);
}
}
class Program
{
static void Main(string[] args)
{
var wssv = new WebSocketServer(IPAddress.Parse("127.0.0.1"), 8080);
wssv.AddWebSocketService<MyWebSocketService>("/myService");
wssv.Start();
Console.WriteLine("WebSocket server started at ws://127.0.0.1:8080/myService");
while (true)
{
Thread.Sleep(1000); }
}
}
}
```
上述代码使用了WebSocketSharp库来实现WebSocket服务端。在代码中,我们定义了一个名为MyWebSocketService的WebSocketBehavior类,用于处理客户端发送的消息。在OnMessage方法中,我们可以获取到客户端发送的消息,并将其回显给客户端。
在Main方法中,我们创建了一个WebSocketServer实例,并将其绑定到本地IP地址127.0.0.1和端口号8080上。然后,我们通过AddWebSocketService方法将MyWebSocketService类注册到WebSocket服务中。最后,我们启动WebSocket服务,并在控制台输出服务的地址。
阅读全文