C#编程 TCP/IP通信
1 服务端 2 3 using System; 4 using System.Collections.Generic; 5 using System.Text; 6 using System.Net; 7 using System.Net.Sockets; 8 9 namespace SocketSer 10 { 11 12 class Program 13 { 14 [STAThread] 15 16 static void Main(string[] args) 17 { 18 int recv; 19 byte[] data = new byte[1024]; 20 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); 21 Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 22 newsock.Bind(ipep); 23 newsock.Listen(10); 24 Console.WriteLine("等待客户端连接中。。。"); 25 Socket client = newsock.Accept(); 26 IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint; 27 Console.WriteLine("已连接的客户端:" + clientip.Address + ",端口" + clientip.Port); 28 string welcome="welcome here!"; 29 data=Encoding.ASCII.GetBytes(welcome); 30 client.Send(data,data.Length,SocketFlags.None);//发送信息 31 while(true) 32 {//用死循环来不断的从客户端获取信息 33 data=new byte[1024]; 34 recv=client.Receive(data); 35 Console.WriteLine("recv="+recv); 36 if (recv==0)//当信息长度为0,说明客户端连接断开 37 break; 38 Console.WriteLine(Encoding.ASCII.GetString(data,0,recv)); 39 client.Send(data,recv,SocketFlags.None); 40 } 41 Console.WriteLine("已断开从"+clientip.Address+"的连接。" ); 42 client.Close(); 43 newsock.Close(); 44 45 } 46 } 47 } 48 49 客户端 50 51 using System; 52 using System.Collections.Generic; 53 using System.Text; 54 using System.Net; 55 using System.Net.Sockets; 56 57 namespace SocketCli 58 { 59 class Program 60 { 61 [STAThread] 62 static void Main(string[] args) 63 { 64 // 65 // TODO: 在此处添加代码以启动应用程序 66 // 67 byte[] data = new byte[1024]; 68 Socket newclient=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); 69 //Console.Write("请输入服务器"); 70 //string ipadd=Console.ReadLine(); 71 //Console.WriteLine(); 72 //Console.Write("please input the server port:"); 73 //int port=Convert.ToInt32(Console.ReadLine()); 74 IPEndPoint ie=new IPEndPoint(IPAddress.Parse("192.168.1.2"),9050);//服务器的IP和端口 75 try 76 { 77 //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。 78 newclient.Connect(ie); 79 } 80 catch(SocketException e) 81 { 82 Console.WriteLine("未连接服务器"); 83 Console.WriteLine(e.ToString()); 84 Console.ReadLine(); 85 return; 86 } 87 int recv = newclient.Receive(data); 88 string stringdata=Encoding.ASCII.GetString(data,0,recv); 89 Console.WriteLine(stringdata); 90 while(true) 91 { 92 string input=Console.ReadLine(); 93 if(input=="exit") 94 break; 95 newclient.Send(Encoding.ASCII.GetBytes(input)); 96 data=new byte[1024]; 97 recv=newclient.Receive(data); 98 stringdata=Encoding.ASCII.GetString(data,0,recv); 99 Console.WriteLine(stringdata); 100 } 101 Console.WriteLine("disconnect from sercer"); 102 newclient.Shutdown(SocketShutdown.Both); 103 newclient.Close(); 104 105 } 106 } 107 }