简体   繁体   English

异步TCP连接C#

[英]async tcp connection C#

        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: 我有一些代码可以接受来自tcp客户端的读取,客户端以这种方式发送消息:

        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: 问题出在messageRecived方法中:

    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? 问题是什么?

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 http://msdn.microsoft.com/zh-cn/library/system.net.sockets.tcpclient.getstream(v=vs.110).aspx

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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