异步tcp连接C#

时间:2014-11-18 05:26:24

标签: c# .net asynchronous tcplistener

        TcpListener tcpServer = new TcpListener(8080);
        tcpServer.Start();
        tcpServer.BeginAcceptTcpClient(new AsyncCallback(this.messageRecived), tcpServer);

我有一些代码接受来自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);

问题在于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);

    }

当我向服务器发送消息时,收到的方法一直运行到这一行:

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

并在下一次迭代中从下一行开始到方法结束。有什么问题?

2 个答案:

答案 0 :(得分:0)

可能是因为您没有关闭来自客户端的流,请参阅以下链接以正确处理来自客户端的流

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

答案 1 :(得分:0)

尝试刷新客户端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()