Question

I have achieved sending message client -> server and actually connecting many clients simultaneously. But what I want to do is i.e. connect 2 clients and make them chat between themselves. And if 3rd client connects - then so he starts chatting with both other clients.

By now I am on the stage of chatting client->server->client separately from another c->s->c. What happens is - I run client1 and everything is OK. Then I run client2 and with it everything is OK, but the 1st client stops working and then the first message I acquire on the 2nd client is the last message that I sent from client1 (but that didn't actually receive back to it from server). So I suppose there's problem with the streams - that the 2 clients somehow acquire each-other's streams. Here is the some parts of the server (relevant ones): TheServer

HandleClientComm(object client) is handling the receive-send operations.

And here is the client side code part, that handles the receive-send operations:TheClient

And I get An unhandled exception of type 'System.OutOfMemoryException' occurred... in in the Server at Byte[] bData = new Byte[BitConverter.ToInt32(bSize, 0)];

sooo... yeah, there's something wrong with the streams (on my opinion). But I don't really know how make the server distinguish between the clients' threads correctly.

I am open for any suggestions.

P.S. I am not posting the code directly here because it will get too long.

Was it helpful?

Solution

This is the first part of HandleClientComm():

private void HandleClientComm(object client)
{
    TcpClient tcpClient = (TcpClient)client;
    NetworkStream stm = clientList[n].GetStream();
    msg = new TheMessage();

You have the tcpClient, which is the client you sent as a parameter, but the NetworkStream is not for that client, but for clientList[n], and n is a class-wide variable. Later in that method, within the while loop, you use:

    stm = clientList[n].GetStream();

As soon as you increase n, all threads running HandleClientComm() will receive and send messages from/to the last client.

The NetworkStream you use in HandleClientComm() should be created from the tpcClient instead, so each thread running HandleClientComm() serves its own client:

    stm = theClient.GetStream();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top