简单的c# TCP通讯(TcpListener)

时间:2022-03-10 22:11:06

 

简单的c# TCP通讯(TcpListener)

C# 的TCP Socket (同步方式)

C# 的TCP Socket (异步方式)

C# 的tcp Socket设置自定义超时时间

C# TCP socket发送大数据包时,接收端和发送端数据不一致 服务端接收Receive不完全

服务器端:

TcpListener listener = new TcpListener(IP, );
listener.Start();

while (true)         {  

TcpClient client = listener.AcceptTcpClient();//接受一个Client

byte[] buffer = new byte[client.ReceiveBufferSize];

NetworkStream stream = client.GetStream();//获取网络流

stream.Read(buffer, 0, buffer.Length);//读取网络流中的数据

stream.Close();//关闭流

client.Close();//关闭Client

receiveString = Encoding.Default.GetString(buffer).Trim('\0');//转换成字符串

Console.WriteLine(receiveString);

}

listener.Stop();

客户端:

TcpClient  client = new TcpClient(ip, );
NetworkStream sendStream = client.GetStream();
Byte[] sendBytes = Encoding.Default.GetBytes(msg);
sendStream.Write(sendBytes, , sendBytes.Length);
sendStream.Flush();
sendStream.Close();//关闭网络流  

client.Close();//关闭客户端