Search code examples
c#socketstcpuwpstream-socket-client

TCP server stops responding after a few requests from client [Windows 10 Universal app, C#, XAML]


I tried to make a little UWP card game to learn how to use TCP, but my server always stops responding to the client after a few connections.

The client sends different messages to the server, like "DrawCard;(name of card)". Interestingly, the first 30-40 messages always reach the server without a problem, but after certain types of messages the server just stops accepting any new ones: For instance, I can draw as many cards as I like, but when I play one, the server stops listening.

I have tried to solve this problem for a few hours now, so I hope someone can help me.

When the app starts, this function is called:

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);
}

This is the event that gets triggered when a connection is received:

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() uses

await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                    () =>
                    {
                         /...
                    });

to edit some ObservableCollections that are bound to UI elements.

The client code is:

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();
        }
    }

In my test scenario, the client app runs on my Windows Mobile phone and the server runs on my PC. The PC doesn´t send any data back to the client apart from returning the received message to make sure it was received correctly.

Thank you very much for any help you can offer. I have tried everything I could find on the Internet, but I didn´t find anything that worked for me.


Solution

  • Thank you very much @Jay Zuo - MSFT! I looked at the official samples and found out that I missed the following line of code:

    CoreApplication.Properties.Add("listener", socketListener);
    

    According to the MS sample, this "save[s] the socket, so subsequent steps can use it." The app works as intended now. Thank you very much for your help, @Rafael and @Jay Zuo - MSFT !