前天去面试,让写这东西
之前的项目也做过这东西,好长时间没看,就给忘了,惭愧!今天重新拾起来,做了个简单的demo
Client端
static void Main(string[] args) { TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(IPAddress.Parse("127.0.0.1"), 8000); //连接到服务器 NetworkStream ns= client.GetStream(); //获取socket网络流对象 byte[] buffer= System.Text.ASCIIEncoding.Default.GetBytes("this message from client"); //字符串编码 ns.Write(buffer, 0, buffer.Length); //发送二进制数组 ns.Close(); client.Close(); }
Server端
static void Main(string[] args) { System.Net.Sockets.TcpListener server = new System.Net.Sockets.TcpListener(8000); //创建服务器的socket server.Start(10); //开始监听 System.Net.Sockets.TcpClient client = server.AcceptTcpClient(); //获取到客户端的TcpClient对象 System.Net.Sockets.NetworkStream ns = client.GetStream(); //获取到网络流NetworkStream对象 string str = new StreamReader(ns).ReadToEnd(); //读取到NetworkStream中的字符串 }