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 }