C# 为什么tcp套接字可以';t用C读取数据#

C# 为什么tcp套接字可以';t用C读取数据#,c#,sockets,tcp,C#,Sockets,Tcp,我使用上面的代码从服务器发送和接收tcp消息,但我没有读取任何内容。 我不想要异步方法。我搜索了一些示例代码,它们是这样写的。有什么我没有意识到的问题吗?谢谢你的帮助 public static byte[] StartClient(string ip, int port, byte[] message, bool needBack, out string errorMsg) { // Data buffer for incoming data. byte

我使用上面的代码从服务器发送和接收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;
        }
    }
公共类MyTcpClient
{
IPEndPoint(远程);;
插座(u插座),;
公共bool IsStopReceive{set;get;}
公共MyTcpClient(字符串ip,int端口)
{
IPAddress=IPAddress.Parse(ip);
_远程=新的IPEndPoint(ipAddress,端口);
_套接字=新套接字(AddressFamily.InterNetwork,
流,ProtocolType.Tcp);
_插座连接(远程);
ThreadPool.QueueUserWorkItem(obj=>{
IsStopReceive=false;
ReceiveMsg();
});
}
公共无效发送(字节[]字节){
_socket.Send(字节);
}
私有内存Stream memoryResult;
私有void ReceiveMsg()
{
MemoryStream memStream=新的MemoryStream();
而(!IsStopReceive)
{ 
字节[]字节=新字节[1024];
int result=_socket.Receive(字节);
如果(结果>0){
memStream.Write(字节,0,结果);
}
否则如果(结果==0){
IsStopReceive=true;
打破
}
}
if(OnMsgReceive!=null){
OnMsgReceive(memStream.GetBuffer());
}
}
公共操作OnMsgReceive{set;get;}
}
上面的代码可以接收数据。当我创建MyTcpClient实例时,它将在连接到目标后打开一个线程来接收数据。
我使用一个操作在数据完成后获取数据。但这是异步的。最重要的是,我不知道为什么我用prev方法遗漏了数据。

服务器代码在哪里?服务器是否确实在发送响应?我建议Sysinternals TCPView监视连接和传输数据量,HWGroup Hercules作为网络终端软件模拟发送方/接收方(它提供TCP客户端和服务器以及上行端点和串行端口连接)。当您说“我什么都没读”时,您的意思是您的代码挂起在对
Receive
的调用中吗?是的。它挂起并等待很长时间,然后以零长度返回array@Klibby服务器是一个PCB,我无法获取服务器的代码,但是wireshark显示了数据。当我在发送方法之前打开一个线程进行接收时,我就可以接收到它。服务器代码在哪里?服务器是否确实在发送响应?我建议Sysinternals TCPView监视连接和传输数据量,HWGroup Hercules作为网络终端软件模拟发送方/接收方(它提供TCP客户端和服务器以及上行端点和串行端口连接)。当您说“我什么都没读”时,您的意思是您的代码挂起在对
Receive
的调用中吗?是的。它挂起并等待很长时间,然后以零长度返回array@Klibby服务器是一个PCB,我无法获取服务器的代码,但是wireshark显示了数据。我可以在send方法之前打开一个线程来接收它
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;}
   }