在NetworkStream / TcpClient上接收套接字

时间:2013-10-11 13:12:28

标签: c# sockets tcplistener

使用套接字我可以这样做来获取字节

 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 byte[] buffer = new byte[1000000];
 s.Receive(buffer, buffer.Length, SocketFlags.None);
 //
 FileStream fs = File.Create("1.jpg");
 fs.Write(buffer, 0, buffer.Length);
 fs.Close();

我使用此代码接收我正在发送的图像的byte []。

我需要将此代码转换为使用TcpClient / NetworkStream来接收发送的byte []     在这里输入代码

1 个答案:

答案 0 :(得分:0)

本规范应与您的规范相同:

var buffer = new byte[100000];
using (TcpClient tcp = new TcpClient(AddressFamily.InterNetwork)
{
    Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
})
{
    await tcp.ConnectAsync("host", 12345);
    if (tcp.Connected)
    {
        using (var stream = tcp.GetStream())
        {
            await stream.ReadAsync(buffer, 0, buffer.Length);
        }

    }
}
using (var fs = File.Create("1.jpg"))
{
    await fs.WriteAsync(buffer, 0, buffer.Length);
}