我尝试制作一个小型UWP纸牌游戏,以了解如何使用TCP,但我的服务器在连接几次后总是停止响应客户端。
客户端向服务器发送不同的消息,例如“DrawCard;(卡名)”。有趣的是,前30-40条消息总是在没有问题的情况下到达服务器,但 某些类型的消息之后,服务器才停止接受任何新消息:例如,我可以绘制尽可能多的卡片。 ,但是当我玩一个时,服务器就会停止收听。
我已经尝试解决这个问题几个小时了,所以我希望有人可以帮助我。
当应用程序启动时,会调用此函数:
public async static Task StartListening()
{
Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener();
socketListener.ConnectionReceived += SocketListener_ConnectionReceived;
await socketListener.BindServiceNameAsync("1337");
//If I leave this line out, it doesn´t even start listening for connections. Any idea why?
await System.Threading.Tasks.Task.Delay(500);
}
这是收到连接时触发的事件:
public async static void SocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender,
Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
{
Stream inStream = args.Socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(inStream);
string request = await reader.ReadLineAsync();
HandleData(request);
////Send the line back to the remote client.
Stream outStream = args.Socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(outStream);
await writer.WriteLineAsync(request);
}
HandleData()使用
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
/...
});
编辑绑定到UI元素的一些ObservableCollections。
客户端代码是:
public async Task SendDataToServer(string data)
{
Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();
Windows.Networking.HostName serverHost = new Windows.Networking.HostName(hostname);
string serverPort = "1337";
await socket.ConnectAsync(serverHost, serverPort);
//Write data to the server.
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
await writer.WriteLineAsync(data);
//Read data from the server.
Stream streamIn = socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
string response = await reader.ReadLineAsync();
}
}
在我的测试场景中,客户端应用程序在我的Windows Mobile手机上运行,服务器在我的PC上运行。除了返回收到的消息以确保正确接收之外,PC不会将任何数据发送回客户端。
非常感谢,您可以提供任何帮助。我已经尝试过在互联网上找到的所有东西,但我找不到任何对我有用的东西。
答案 0 :(得分:1)
非常感谢@Jay Zuo - MSFT! 我查看了官方样本,发现我错过了以下代码:
WARNING: NEGOTIATE authentication error: No valid credentials provided (Mechanism level: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt))
WARNING: KERBEROS authentication error: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)
WARNING: NTLM authentication error: Credentials cannot be used for NTLM authentication: org.apache.http.auth.UsernamePasswordCredentials
根据MS示例,这个“保存[s]套接字,因此后续步骤可以使用它。” 该应用程序现在按预期工作。非常感谢你的帮助,@ Rafael和@Jay Zuo - MSFT!