简体   繁体   中英

C# - client streaming in multithreaded server

I have achieved sending message client -> server and actually connecting many clients simultaneously. But what I want to do is ie 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM