我正在尝试为我的UWP Windows 10应用程序开发一个web套接字服务器应用程序。
这是我的代码:
class Server
{
public async void Start()
{
MessageWebSocket webSock = new MessageWebSocket();
//In this case we will be sending/receiving a string so we need to set the MessageType to Utf8.
webSock.Control.MessageType = SocketMessageType.Utf8;
//Add the MessageReceived event handler.
webSock.MessageReceived += WebSock_MessageReceived;
//Add the Closed event handler.
webSock.Closed += WebSock_Closed;
Uri serverUri = new Uri("ws://127.0.0.1/motion");
try
{
//Connect to the server.
await webSock.ConnectAsync(serverUri);
//Send a message to the server.
await WebSock_SendMessage(webSock, "Hello, world!");
}
catch (Exception ex)
{
//Add code here to handle any exceptions
}
}
//The MessageReceived event handler.
private void WebSock_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
{
DataReader messageReader = args.GetDataReader();
messageReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
string messageString = messageReader.ReadString(messageReader.UnconsumedBufferLength);
//Add code here to do something with the string that is received.
}
//The Closed event handler
private void WebSock_Closed(IWebSocket sender, WebSocketClosedEventArgs args)
{
//Add code here to do something when the connection is closed locally or by the server
}
//Send a message to the server.
private async Task WebSock_SendMessage(MessageWebSocket webSock, string message)
{
DataWriter messageWriter = new DataWriter(webSock.OutputStream);
messageWriter.WriteString(message);
await messageWriter.StoreAsync();
}
}
此处出错:等待webSock.ConnectAsync(serverUri)
出现此错误:
未找到(404)。(HRESULT异常:0x80190194)
我对它没有任何个人经验,但您可能想试试IotWeb HTTP服务器。它似乎是一个便携式嵌入式HTTP和web套接字服务器,也支持UWP,可以在Windows Store和Windows 10 IoT Core应用程序中运行。
从它的存储库来看,它相当新,并不完全成熟,也没有很多可用的文档或样本。不过,还有一个NuGet包可用。
不幸的是,我还没有找到其他选择。
代码
await webSock.ConnectAsync(serverUri);
是尝试连接到ws://127.0.0.1/motion上的现有服务器,而不是在此地址上部署服务器。
您可以在以下链接中寻找构建c#WebSocket服务器的方法:
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_serverhttp://www.codeproject.com/Articles/57060/Web-Socket-Server