用的c#自带的对socket进一步封装的函数,下面是代码:
服务端:
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace tcpServer { class Program { //服务器端 static void Main(string[] args) { TcpListener listener = new TcpListener(IPAddress.Parse("192.168.1.104"), 2222); listener.Start();//开始监听 TcpClient client = listener.AcceptTcpClient();//获取客户端的socket NetworkStream stream = client.GetStream();//获取流 byte[] data = new byte[1024]; while (true) { int length = stream.Read(data, 0, 1024); string message = Encoding.UTF8.GetString(data, 0, length); Console.WriteLine("消息:" + message); } /* //关闭程序不要忘了做下面操作(指有退出事件的时候) stream.Close(); client.Close(); listener.Stop(); */ } } }
客户端:
using System; using System.ComponentModel; using System.Net; using System.Net.Sockets; using System.Text; namespace tcpClient { //客户端 class Program { static void Main(string[] args) { //当我们创建tcpclient对象,服务器的ip和端口号 TcpClient client = new TcpClient("192.168.1.104", 2222); NetworkStream stream = client.GetStream();//通过网络流进行数据的交换 //read用来读取数据,write用来发送数据 while (true) { string message = Console.ReadLine(); byte[] data = Encoding.UTF8.GetBytes(message); stream.Write(data, 0, data.Length); } /* //实际使用过程中在程序关闭的时候不要忘了关闭连接 stream.Close(); client.Close(); */ } } }
结果: