我写了一个简单的 WebSocketServer,我在 MSDN 网站上找到了它。但它不起作用。你能解释一下我应该如何运行这个简单的项目,因为我启动了它但什么也没发生。
服务器
namespace WebSocketServer
{
class Program
{
static void Main(string[] args)
{
var task1 = Run();
// Console.ReadLine();
}
public static async Task Run()
{
HttpListener s = new HttpListener();
s.Prefixes.Add("http://localhost:8000/ws");
s.Start();
var hc = await s.GetContextAsync();
if (!hc.Request.IsWebSocketRequest)
{
hc.Response.StatusCode = 400;
hc.Response.Close();
return;
}
var wsc = await hc.AcceptWebSocketAsync(null);
var ws = wsc.WebSocket;
for (int i = 0; i != 10; ++i)
{
// await Task.Delay(20);
var time = DateTime.Now.ToLongTimeString();
var buffer = Encoding.UTF8.GetBytes(time);
var segment = new ArraySegment<byte>(buffer);
await ws.SendAsync(segment, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
}
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
}
}
}
客户
namespace WebSocketClient
{
class Program
{
static void Main(string[] args)
{
var clientTask1 = Client();
Console.ReadLine();
}
static async Task Client()
{
ClientWebSocket ws = new ClientWebSocket();
var uri = new Uri("ws://localhost:8000/ws/");
await ws.ConnectAsync(uri, CancellationToken.None);
var buffer = new byte[1024];
while (true)
{
var segment = new ArraySegment<byte>(buffer);
var result = await ws.ReceiveAsync(segment, CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await ws.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "I don't do binary", CancellationToken.None);
return;
}
int count = result.Count;
while (!result.EndOfMessage)
{
if (count >= buffer.Length)
{
await ws.CloseAsync(WebSocketCloseStatus.InvalidPayloadData, "That's too long", CancellationToken.None);
return;
}
segment = new ArraySegment<byte>(buffer, count, buffer.Length - count);
result = await ws.ReceiveAsync(segment, CancellationToken.None);
count += result.Count;
}
var message = Encoding.UTF8.GetString(buffer, 0, count);
Console.WriteLine(">" + message);
}
}
}
}
我需要创建一个简单的网站,该网站将从 WebSocketServer 获取一些数据(例如时间)并将其显示在此页面上。我写了一些代码,但什么也没发生
<html>
<body>
<script type ="text/javascript">
var ws = new WebSocket("ws://localhost:8000/ws/");
ws.onmessage = function (args)
{
var time = args.data;
};
</script>
</body>
</html>
最佳答案
在服务器端,Run
是一个 async
方法;一旦到达结果尚未完成的第一个 await
,它将立即返回给调用者。这意味着您的服务器将退出 Main
,并且在没有任何其他主(非工作线程)线程的情况下,您的服务器 将终止 。 Console.ReadLine
的存在是有原因的。放回去:
static void Main(string[] args)
{
var task1 = Run();
Console.WriteLine("Press return to exit the server");
Console.ReadLine();
}
关于c# - WebSocketServer MSDN 示例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20044960/