我写了一个简单的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获取一些数据(例如Time)并在此页面上显示它。我写了一些代码,但没有发生任何事情
<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>
答案 0 :(得分:8)
在服务器上,Run
是async
方法;一旦它到达第一个await
结果尚未完成,它将返回到调用者。这意味着您的服务器将退出Main
,并且在没有任何其他主(非工作)线程的情况下,您的服务器将终止。 Console.ReadLine
是有原因的。把它放回去:
static void Main(string[] args)
{
var task1 = Run();
Console.WriteLine("Press return to exit the server");
Console.ReadLine();
}