为什么tcp套接字无法用C#读取数据

时间:2015-12-29 16:30:00

标签: c# sockets tcp

public static byte[] StartClient(string ip, int port, byte[] message, bool needBack, out string errorMsg)
    {
        // Data buffer for incoming data.
        byte[] bytes = new byte[1024];

        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            IPAddress ipAddress = IPAddress.Parse(ip);
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP  socket.
            Socket sender = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect the socket to the remote endpoint. Catch any errors.
            try
            {
                sender.Connect(remoteEP);

                // Send the data through the socket.
                int bytesSent = sender.Send(message);
                if (needBack)
                {
                    // Receive the response from the remote device.
                    int bytesRec = sender.Receive(bytes);
                    byte[] array = new byte[bytesRec];
                    Array.Copy(bytes, array, bytesRec);
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                    errorMsg = "";
                    return array;
                }
                else
                {
                    errorMsg = "";
                    return null;
                }
            }
            catch (ArgumentNullException ane)
            {
                errorMsg = string.Format("ArgumentNullException : {0}", ane.ToString());
                return null;
            }
            catch (SocketException se)
            {
                errorMsg = string.Format("SocketException : {0}", se.ToString());
                return null;
            }
            catch (Exception e)
            {
                errorMsg = string.Format("Unexpected exception : {0}", e.ToString());
                return null;
            }
        }
        catch (Exception e)
        {
            errorMsg = string.Format("Unexpected exception : {0}", e.ToString());
            return null;
        }
    }

我使用上面的代码从服务器发送和接收tcp消息。但我什么也没读。 我不想要一个异步方法。我搜索了一些示例代码,它们是这样编写的。有没有什么不对的,我没有意识到。谢谢你的帮助。

public class MyTcpClient
{
    IPEndPoint _remote;
    Socket _socket;
    public bool IsStopReceive{set;get;}
    public MyTcpClient(string ip, int port)
    {
        IPAddress ipAddress = IPAddress.Parse(ip);
        _remote = new IPEndPoint(ipAddress, port);
        _socket = new Socket(AddressFamily.InterNetwork,
               SocketType.Stream, ProtocolType.Tcp);
        _socket.Connect(_remote);
        ThreadPool.QueueUserWorkItem(obj=>{
            IsStopReceive = false;
            ReceiveMsg();
        });
    }

    public void Send(byte[] bytes) {
        _socket.Send(bytes);
    }

    private MemoryStream memoryResult;
    private void ReceiveMsg()
    {
        MemoryStream memStream = new MemoryStream();
        while (!IsStopReceive)
        { 
            byte[] bytes=new byte[1024];
            int result = _socket.Receive(bytes);
            if (result > 0) {
                memStream.Write(bytes, 0, result);
            }
            else if (result == 0) {
                IsStopReceive = true;
                break;
            }
        }
        if (OnMsgReceive != null) {
            OnMsgReceive(memStream.GetBuffer());
        }
    }

    public Action<byte[]> OnMsgReceive{set;get;}
   }

上面的代码可以接收数据。当我创建一个MyTcpClient实例时,它将打开一个线程,在连接到目标后接收数据。 我在完成后使用Action来获取数据。但这是异步的。最重要的是我不知道为什么我错过了使用prev方法的数据。

0 个答案:

没有答案