需要引用 using System.Net; using System.Net.Sockets;
1 namespace TCPServer { 2 class Program { 3 static void Main(string[] args) { 4 int port = 888;//端口 5 TcpClient tcpClient;//创建TCP连接对象(存入客服端所链接) 6 IPAddress[] serverIP= Dns.GetHostAddresses("127.0.0.1");//定义IP地址 7 IPAddress localAddres = serverIP[0];//Ip地址; 8 TcpListener tcpListener = new TcpListener(localAddres, port);//监听套接字 9 tcpListener.Start();//开始监听10 Console.WriteLine("服务器启动成功,等待用户接入。。。");//输出信息11 try {12 tcpClient = tcpListener.AcceptTcpClient();//每接收一个客服端生成一个TcpClient13 NetworkStream networkStream = tcpClient.GetStream();//获取网络数据流14 BinaryReader reader = new BinaryReader(networkStream);//定义数据读取对象15 BinaryWriter writer = new BinaryWriter(networkStream);//定义数据写入对象16 while(true) {17 try {18 string strReader = reader.ReadString();//接收消息19 string[] strReaders = strReader.Split(new char[] { ' ' });//截取客服端信息20 Console.WriteLine("有客服端接入,客户IP:" + strReaders[0]);//输出接收客服端IP地址21 string strWriter = "我是服务器,欢迎光临";//定义服务端要写的内容22 Console.WriteLine("来自客服端的消息:" + strReaders[1]);//输出接收的消息23 writer.Write(strWriter);//向对方发送消息24 }25 catch {26 break;27 }28 }29 }30 catch {31 Console.WriteLine("接收数据失败");32 }33 34 }35 }36 }
1 namespace TCPClient { 2 class Program { 3 static void Main(string[] args) { 4 TcpClient tcpClient = new TcpClient();//创建一个TcpClient对象,自动分配主机IP地址和端口号 5 tcpClient.Connect("127.0.0.1", 888);//连接服务器,其IP和端口号为127.0.0.1和888 6 if (tcpClient != null) { 7 Console.WriteLine("连接服务器成功"); 8 NetworkStream networkStream = tcpClient.GetStream();//获取网络数据流 9 BinaryReader reader = new BinaryReader(networkStream);//定义数据读取对象10 BinaryWriter writer = new BinaryWriter(networkStream);//定义数据写入对象11 string localip = "127.0.0.1";//存储本机IP,默认值为127.0.0.112 IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());//获取所有Ip地址13 foreach (var item in ips) {14 if (!item.IsIPv6SiteLocal)//如果不是ipv615 localip = item.ToString();16 }17 writer.Write(localip + " 你好服务器,我是客服端");//向服务器发送消息18 while (true) {19 try {20 string strReader = reader.ReadString();//接收服务器发送的数据21 if(strReader!=null) {22 Console.WriteLine("来自服务器的消息:" + strReader);//输出接收服务器的消息23 }24 }25 catch {26 break;//出错退出循环27 }28 }29 }30 else {31 Console.WriteLine("连接服务器错误");32 }33 }34 }35 }
上述代码,通俗易懂,注释详细,适合小白学习。