一.服务器
static void Main(string[] args)
{
//1.声明一个listener:套接字和接口都绑定好了
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.0.100"), 7788);
//2.开始监听
listener.Start();
//3.等待客户接入
TcpClient tcpClient = listener.AcceptTcpClient();
//4.创建一个流用来收发数据
NetworkStream stream = tcpClient.GetStream();
//读入,也就是接受一个数据
byte[] data = new byte[1024];
int length = stream.Read(data, 0, 1024);
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine(message);
//5.关闭相应的流和监听器
stream.Close();
listener.Stop();
Console.ReadKey();
}
二.客户端
static void Main(string[] args)
{
//1.声明一个客户端
TcpClient tcpClient = new TcpClient("192.168.0.100",7788);
//2.声明一个流用来读写数据
NetworkStream stream= tcpClient.GetStream();
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
//3.关闭相应的东西
stream.Close();
tcpClient.Close();
Console.ReadKey();
}