打开命名空间
using System.Net; using System.Net.Sockets;
服务端代码:
1 static void Main(string[] args) 2 { 3 int port = 2000; 4 string host = "127.0.0.1"; 5 6 IPAddress ip = IPAddress.Parse(host); 7 IPEndPoint ipe = new IPEndPoint(ip, port); 8 9 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 10 socket.Bind(ipe); 11 socket.Listen(0); //监听 12 Console.WriteLine("waiting......."); 13 14 //接受来自客户端发送的信息 15 Socket temp = socket.Accept(); //创建新的socket用于和客户端通信 16 Console.WriteLine("ok..."); 17 string recstr = ""; 18 byte[] recbyte = new byte[1024]; 19 int bytes; 20 bytes = temp.Receive(recbyte, recbyte.Length, 0); 21 recstr += Encoding.ASCII.GetString(recbyte, 0, bytes); 22 23 //给客户端返回信息 24 Console.WriteLine("server get message:{0}", recstr); 25 string sendstr = "client send message successful"; 26 byte[] by = Encoding.ASCII.GetBytes(sendstr); 27 temp.Send(by, by.Length, 0); //发送 28 temp.Close(); //关闭 29 socket.Close(); 30 Console.ReadLine(); 31 32 }
客户端代码:
1 static void Main(string[] args) 2 { 3 try 4 { 5 int port = 2000; 6 string host = "127.0.0.1"; 7 8 IPAddress ip = IPAddress.Parse(host); 9 IPEndPoint iped = new IPEndPoint(ip, port); 10 11 Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 12 Console.WriteLine("waiting......"); 13 soc.Connect(iped); //连接 14 15 //向服务端发送消息 16 string sendstr = "hello,this is client message"; 17 byte[] bytes = Encoding.ASCII.GetBytes(sendstr); 18 Console.WriteLine("send message"); 19 soc.Send(bytes); 20 21 //接受由服务端返回的信息 22 string recstr = ""; 23 byte[] recbyte = new byte[1024]; 24 int bytess; 25 bytess = soc.Receive(recbyte, recbyte.Length, 0); 26 recstr += Encoding.ASCII.GetString(recbyte, 0, bytess); 27 Console.WriteLine("get message:{0}", recstr); 28 soc.Close(); 29 30 } 31 catch (Exception ex) 32 { 33 Console.WriteLine("error"); 34 } 35 Console.WriteLine("press enter exit"); 36 Console.ReadLine(); 37 }
参考博客园文章
|
请发表评论