我从UWP应用程序访问远程websocket服务器('ws://172.17.35.104:8080 / WebsocketHttpListenerDemo')时遇到了问题。
DataWriter StoreAsync()抛出异常。在意外的时间调用了一个方法。 (来自HRESULT的异常:0x8000000E)
请参考以下示例代码(客户端):
private async void Button_Click(object sender, RoutedEventArgs e)
{
Connect("ws://172.17.35.104:8080/WebsocketHttpListenerDemo").Wait();
}
public async Task Connect(string uri)
{
await Task.Delay(100); //wait for a sec, so server starts and ready to accept
// await Task.Delay(TimeSpan.FromSeconds(1));
messageWebSocket = new Windows.Networking.Sockets.MessageWebSocket();
messageWebSocket.Control.MessageType = Windows.Networking.Sockets.SocketMessageType.Utf8;
messageWebSocket.MessageReceived += WebSocket_MessageReceived;
messageWebSocket.Closed += WebSocket_Closed;
try{
Task connectTask = messageWebSocket.ConnectAsync(new Uri(uri)).AsTask();
await connectTask.ContinueWith(_ => this.SendMessageUsingMessageWebSocketAsync("Hello, World!"));
await Task.Delay(1000);
}
catch (Exception ex)
{}
finally
{ }
}
private async Task SendMessageUsingMessageWebSocketAsync(string message)
{
try
{
using (var dataWriter = new DataWriter(this.messageWebSocket.OutputStream))
{
dataWriter.WriteString(message);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
}
catch (Exception ex)
{}
}
服务器端代码:
WebsocketServer websocketServer = new WebsocketServer(); websocketServer.Start( “http://172.17.35.104:8080/WebsocketHttpListenerDemo/”);
------------
public async void Start(string httpListenerPrefix)
{
HttpListener httpListener = new HttpListener();
httpListener.Prefixes.Add(httpListenerPrefix);
httpListener.Start();
Console.WriteLine("Listening...");
while (true){
HttpListenerContext httpListenerContext = await httpListener.GetContextAsync();
ProcessRequest(httpListenerContext);
}
}
private async void ProcessRequest(HttpListenerContext httpListenerContext)
{
WebSocketContext webSocketContext = await httpListenerContext.AcceptWebSocketAsync(subProtocol: null);
WebSocket webSocket = webSocketContext.WebSocket;
byte[] receiveBuffer = new byte[1024];
while (webSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer),
CancellationToken.None);
}
}