4

I'm new with socket and trying to write a Client-Server application My applicationhas those two main methods :

SERVER running on separate Thread :

    public void socketListener()
    {
        byte[] StreamMessage = new byte[9632];
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint localEndPoint =new IPEndPoint(IPAddress.Any , ControlLayer.GlobalParam.PEER2PEER_PORT);
            listener.Bind(localEndPoint);
            listener.Listen(10);

            while (true)
            {
                Socket Handler = listener.Accept();
                //int ByteRec = Handler.Receive(StreamMessage);

                int MessageLength;
                MessageLength = Handler.Receive(StreamMessage, 0, StreamMessage.Length, SocketFlags.None);
                //return MessageLength;

               // string message = System.Text.Encoding.Default.GetString(StreamMessage);
                string message = System.Text.Encoding.UTF8.GetString(StreamMessage);

                OnDataRecievedFromRemotePeer(this, message, "TcpServer");//send data to screen
                Task.Run(() => { ParseMessage(message, Handler); });
            }
    }

once data arrives I prase it collect data and send it using Client CLIENT :

    public void Write(string message)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(CreateClient), message);
    }

    private void CreateClient(object message)
    {
        try
        {
            peerClient = new TcpClient();
            peerClient.Connect(remoteIP, 6001/*TODO remove this */);
            netStream = peerClient.GetStream();//<- Exception 
            StreamWriter sw = new StreamWriter(netStream);
            sw.Write((string)(message));
            netStream.Close();
            peerClient.Close();
        }
        catch(Exception ex)
        {
            //TODO :
        }
    }

Each station is symmetrical and have those two methods

I can tell that the server is working and accepting socket and data but once I want to respond back I get exception in the Line marked in the CreateClient
stream was not writable and when looking on the netStream it is written that I have ObjectDisposed Exception . What can be the cause of that ?

Also please inform me if more code is needed

LordTitiKaka
  • 2,087
  • 2
  • 31
  • 51

1 Answers1

2

You have a classical race here between the server closing the connection before the client has processed the response of the server.
TCP is a "polite" protocol, which means that you can not perform a fire and forget action on the server. The connection needs to be alive on both ends until both sides have processed all messages. Thus either the client needs to send an acknowledge/logout, so that the server can close the connection or at least the server has to wait x seconds until closing it.

weismat
  • 7,195
  • 3
  • 43
  • 58
  • Sorry for stupid question ,but where in the server I close connection? also , Do you think my logic is good practice for this type of applications ? – LordTitiKaka Jul 09 '14 at 08:39
  • The classical way is to have one thread or task per client on the server. Currently your client connection exists only during one iteration of the while loop. I usually use sth like this: while (true) { TcpClient client = _tcpListener.AcceptTcpClient(); Log.Info("New client connected"); var clientThread = new Thread(HandleClientComm) {IsBackground = true}; clientThread.Start(client); } – weismat Jul 09 '14 at 08:42
  • can you please post a short code so I can "step by step" the life out of him ? :) – LordTitiKaka Jul 09 '14 at 08:44
  • You are looking at a race/multithreading, so you have to be careful with "step by step". Have a look at http://www.codeproject.com/Articles/1415/Introduction-to-TCP-client-server-in-C if you want step by step/minimal code. – weismat Jul 09 '14 at 08:49
  • Thank you very much for your help but the example you gave looks very identical to my code , can you please elaborate of what you needed to be done and maybe short (even pseudo) code to give me the right direction – LordTitiKaka Jul 09 '14 at 10:42
  • The example has a response message from the server to the client. I miss this part in your code. – weismat Jul 09 '14 at 10:48
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/57009/discussion-between-weismat-and-lordtitikaka). – weismat Jul 09 '14 at 10:57
  • please dont forget about me ! my boss will have my head – LordTitiKaka Jul 09 '14 at 12:40