//server端 using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; namespace Project1 { class Class2 { static void Main() { try { int port = 2000; string host = "127.0.0.1"; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//創建一個Socket類 s.Bind(ipe);//綁定2000端口 s.Listen(0);//開始監聽 Console.WriteLine("Wait for connect"); Socket temp = s.Accept();//為新建連接創建新的Socket。 Console.WriteLine("Get a connect"); string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//從客戶端接受信息 recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes); Console.WriteLine("Server Get Message:{0}",recvStr);//把客戶端傳來的信息顯示出來 string sendStr = "Ok!ClIEnt Send Message Sucessful!"; byte[] bs = Encoding.ASCII.GetBytes(sendStr); temp.Send(bs, bs.Length, 0);//返回客戶端成功信息 temp.Close(); s.Close(); } catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: {0}", e); } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } Console.WriteLine("Press Enter to Exit"); Console.ReadLine(); } } }
上面的例子是用的Socket類,System.Net.Socket命名空間還提供了兩個抽象高級類TCPClient和UDPClIEnt和用於通訊流處理的NetWorkStream,讓我們看下例子