async tcp connection C#

225 Views Asked by At
        TcpListener tcpServer = new TcpListener(8080);
        tcpServer.Start();
        tcpServer.BeginAcceptTcpClient(new AsyncCallback(this.messageRecived), tcpServer);

I have some code for accept reading from tcp client, client send massage in this way:

        TcpClient client = new TcpClient("192.168.0.2", 8080)
        string Str = "it's work";
        byte[] Buffer = Encoding.ASCII.GetBytes(Str);
        client.GetStream().Write(Buffer, 0, Buffer.Length);

the problem is in messageRecived method:

    public void messageRecived(IAsyncResult result)
    {
        byte[] data = new byte[20000];
        string outData;

        TcpListener server = (TcpListener)result.AsyncState;

        server.AcceptTcpClient().GetStream().Read(data, 0, server.Server.ReceiveBufferSize);

        outData = Encoding.ASCII.GetString(data);
        addLog(outData);

    }

When i send message to server the method received run until to this line:

server.AcceptTcpClient().GetStream().Read(data, 0, server.Server.ReceiveBufferSize);

and in the next iteration it begin from next line to the end of method. What is the problem?

2

There are 2 best solutions below

1
On BEST ANSWER

probably because you are not closing stream from client, please refer to below link to properly dispose stream from client

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream(v=vs.110).aspx

0
On

Try to flush the client Stream.

TcpClient client = new TcpClient("192.168.0.2", 8080)
string Str = "it's work";
byte[] Buffer = Encoding.ASCII.GetBytes(Str);
var stream = client.GetStream()
stream.Write(Buffer, 0, Buffer.Length);
stream.Flush()