qq_33709062
创可贴男孩
2017-07-22 16:20

c# 做TCP服务器端接受数据时无法获取发送的数据,当客户端断连后数据才上传

  • c#
  • 网络编程

private void Listen()
{
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(serverIP, 3588));

        //不断监听端口
        while (true)
        {
            listener.Listen(1);
            Socket socket = listener.Accept();//监听到连接
            //Socket socket = listener.BeginAccecpt(new AsyncCallback(Accept), listener);
            //listener.BeginAccept(new AsyncCallback(AcceptCallBack), listener);//监听连接状态

            //while(true)
            //{
            //    NetworkStream ntwStream = new NetworkStream(socket);
            //    StreamReader strmReader = new StreamReader(ntwStream);
            //    Invoke(new PrintRecvMssgDelegate(PrintRecvMssg),
            //        new object[] { strmReader.ReadToEnd() });
            //    listener.Listen(1);
            //    socket = listener.Accept();
            //}
            NetworkStream ntwStream = new NetworkStream(socket);//监听到连接
            StreamReader strmReader = new StreamReader(ntwStream);
            Invoke(new PrintRecvMssgDelegate(PrintRecvMssg), new object[] { strmReader.ReadToEnd() });
            socket.Close();
            //MessageBox.Show("11");

        }

        //程序的listener一直不关闭
        //listener.Close();
    }
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答