代码之家  ›  专栏  ›  技术社区  ›  Martijn

C从套接字读取二进制数据

  •  3
  • Martijn  · 技术社区  · 16 年前

    我正在开发一个应用程序,它从套接字读取二进制数据并将其写入套接字。所以首先我用tcpclient创建一个套接字。但我一直在从插座上读取数据。关于如何从套接字中读取二进制数据,是否有任何代码示例?

    具体来说,有两件事我不明白。首先,我如何知道消息是否“已接收”?我需要为此创建某种循环吗?第二:什么是读取这些数据的最好方法,因为我接收的数据是二进制的,而不仅仅是普通的字符串。

    谢谢

    4 回复  |  直到 16 年前
        1
  •  5
  •   badbod99    16 年前

    TCPClient documentation

    // Get the stream
    NetworkStream stream = client.GetStream();
    Byte[] data = new Byte[256];
    
    // String to store the response ASCII representation.
    String responseData = String.Empty;
    
    // Read the first batch of the TcpServer response bytes.
    int bytes = stream.Read(data, 0, data.Length);
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    

    GetStream TCPClient


    DATA

    GetString GetBytes

        3
  •  0
  •   Patrick angularsen    16 年前

    NetworkStream stream = client.GetStream();

    public void send(NetworkStream stream, byte[] buf) {
        stream.Write(BitConverter.GetBytes(buf.Length), 0, 4);
        stream.Write(buf, 0, buf.Length);
    }
    
    public byte[] receive(NetworkStream stream) {
        byte[] lengthBytes = new byte[4];
        int read = stream.Read(lengthBytes, 0, 4);
        // read contains the number of read bytes, so we can check it if we want
        int length = BitConverter.GetInt32(lengthBytes);
        byte[] buf = new byte[length];
        stream.Read(buf, 0, buf.length);
        return buf;
    }