示常式序是同步套接字程式,功能很簡單,只是客戶端發給伺服器一條信息,伺服器向客戶端返回一條信息,是一個簡單示例,也是一個最基本的socket編程流程。 簡單步驟說明: 1.用指定的port, ip 建立一個EndPoint對象 2.建立一個Socket對象; 3.用Socket對象的Bind()方法 ...
示常式序是同步套接字程式,功能很簡單,只是客戶端發給伺服器一條信息,伺服器向客戶端返回一條信息,是一個簡單示例,也是一個最基本的socket編程流程。
簡單步驟說明:
1.用指定的port, ip 建立一個EndPoint對象
2.建立一個Socket對象;
3.用Socket對象的Bind()方法綁定EndPoint
4.用Socket對象的Listen()方法開始監聽
5.接收到客戶端的連接,用socket對象的Access()方法創建新的socket對象用於和請求的客戶端進行通信
6.通信結束後記得關閉socket
代碼:
1 int port = 2000; 2 string host = "127.0.0.1"; 3 // create endPoint 4 IPAddress ip = IPAddress.Parse(host); 5 IPEndPoint ipe = new IPEndPoint(ip, port); 6 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 7 s.Bind(ipe); 8 9 s.Listen(0); 10 11 Console.WriteLine("wait a client to connect.."); 12 Socket temp = s.Accept(); 13 Console.WriteLine("create a connection"); 14 15 //receive message 16 string recvStr = ""; 17 byte[] recvBytes= new byte[1024]; 18 int bytes; 19 bytes = temp.Receive(recvBytes, recvBytes.Length, 0); 20 recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes); 21 Console.WriteLine("server have get message:{0}",recvStr ); 22 23 // send message 24 string sendStr = "ok! client send message cuccessful"; 25 byte[] bs = Encoding.ASCII.GetBytes(sendStr); 26 temp.Send(bs, bs.Length, 0); 27 28 //end 29 temp.Close(); 30 s.Close(); 31 32 Console.WriteLine("end socket com!"); 33 Console.ReadLine();
客戶端:
1.用指定的port, ip 建立一個EndPoint對象
2.建立一個socket對象
3.用socket對象的Connect()方法以上面的EndPoint對象作為參數,向伺服器發送連接請求;
4.如果連接成功,就用socket對象的Send()方法向伺服器發送信息
5.用socket對象的Receive()方法接收伺服器發來的信息
6.通信結束記得關閉socket:
代碼::
//init server port and ip int port = 2000; string host = "127.0.0.1"; IPAddress ip = IPAddress.Parse(host); // create ipendpoint IPEndPoint ipe = new IPEndPoint(ip, port); // create client sockets Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Console.WriteLine("Connecting..."); // connect to server c.Connect(ipe); // send to server string sendStr = "Hello, this is a socket test"; byte[] bs = Encoding.ASCII.GetBytes(sendStr); Console.WriteLine("Send Message"); c.Send(bs, bs.Length, 0); // receive a message from server string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = c.Receive(recvBytes, recvBytes.Length, 0); recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes); Console.WriteLine("Client get message:{0}", recvStr); //close Client c.Close(); } catch (ArgumentException e) { Console.WriteLine("argumentNullException:{0}",e); } catch (SocketException e) { Console.WriteLine("socketException:{0}",e); } Console.WriteLine("Press enter to exit"); Console.ReadLine();
來源:內容來自網路