C#中的TCP套接字服务器/客户端 - 被动接收数据

时间:2014-09-06 22:44:45

标签: c# sockets tcp

我有一些代码,我正在尝试接收有关响应的数据,以及被动地接收数据。但是,我目前无意中接收数据的尝试失败了。我想知道是否有人可以为我阐明它。

static void Listen()
    {
        while (_socket.Connected)
        {
            try
            {
                byte[] receivedBuffer = new byte[2048];
                int bytesReceived = _socket.Receive(receivedBuffer);
                byte[] data = new byte[bytesReceived];

                Array.Copy(receivedBuffer, data, bytesReceived);

                Console.WriteLine("Server: \"" + Encoding.ASCII.GetString(data) + "\"");
            }

            catch (SocketException e) { Console.WriteLine(e.Message); }
        }
    }

因此,当用户在控制台中输入文本时,希望从服务器控制台被动地捕获数据。客户端通过TCP套接字连接到服务器。目前这些数据没有被捕获,并没有达到目标。相反,它保留在此方法捕获的缓冲区内。

static void Send()
    {
        while (_socket.Connected)
        {
            try
            {
                Console.Write("Enter Request: ");

                string request = Console.ReadLine();
                byte[] buffer = Encoding.ASCII.GetBytes(request);
                _socket.Send(buffer);

                byte[] receivedBuffer = new byte[2048];
                int bytesReceived = _socket.Receive(receivedBuffer);
                byte[] data = new byte[bytesReceived];

                Array.Copy(receivedBuffer, data, bytesReceived);

                Console.WriteLine(Encoding.ASCII.GetString(data));
            }

            catch (SocketException) { }
        }
    }

0 个答案:

没有答案