服务端代码
TcpListener tcpListener=new TcpListener(IPAddress.Parse("192.168.1.1"),9000);
tcpListener.Start();//启动服务
While(true)
{
TcpClient tcpClient=tcpListener.AcceptTCPClient();//收到链接
NetWorkStream steam=tcpClient.GetStream();
byte[] receiveData=new byte[1024];
var len=stream.Read(receiveData,0,1024);
string receiveString=Encoding.UTF8.GetString(receiveData,0,len);//字节数据解析成字符串
string sendString="收到信息";
var sendData=Encoding.UTF8.GetBytes(sendString);
stream.Write(sendData,0,sendData.Length);//向客户端发送信息
}
客户端代码
TCPClient tcpClient=new TCPClient();
tcpClient.Connect("192.168.1.1",9000);
NetWorkStream steam=tcpClient.GetStream();
string sendString="请求消息";
var sendData=Encoding.UTF8.GetBytes(sendString);
steam.Write(sendData,0,sendData.Length);//向服务端发送消息
byte[] receiveData=new byte[1024];
var len=stream.Read(receiveData,0,1024);
var receiveString=Encoding.UTF8.GetString(receiveData,0,len);//将接收服务端返回的字节解析成字符串
tcpClient.Close();
tcpClient.Dispose();
标签:tcpClient,sendData,通讯,receiveData,C#,UTF8,TCP,sendString,var From: https://www.cnblogs.com/follow-discoverer/p/17513870.html