Socket編程服務端和用戶端代碼__編程

來源:互聯網
上載者:User

//伺服器端Socket程式 建一個main程式接受用戶端的訊息 public void ServerSocket() { Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//(1)首先在伺服器端定義一個通訊端(socket),使用Tcp協議 listener.Bind(new IPEndPoint(IPAddress.Any, 2112));//(2)其次設定該通訊端的綁定IP,接受從任意IP地址發往連接埠2112的訊息 listener.Listen(100);//(3)將通訊端置為監聽狀態,並設定監聽隊列為100 while (true) //死迴圈,即不發生異常中斷的情況下一直接受訊息 { string receiverAllStr = string.Empty; Socket socket = listener.Accept();//(4)Create a new Socket for a newly created connection while (true) { byte[] receiveBytes = new byte[1024]; int numBytes = socket.Receive(receiveBytes); //(5)從socket中接受訊息,將接收到的訊息寫入已定義的位元組數組中 string receiveStr = Encoding.ASCII.GetString(receiveBytes, 0, numBytes); receiverAllStr += receiveStr; if (receiveStr.IndexOf("[FINAL]") > -1) { Console.WriteLine(receiverAllStr); break; } } string replySuccess = "The data can be successfullly received!";//非必須 byte[] byteStr = Encoding.ASCII.GetBytes(replySuccess);//非必須 socket.Send(byteStr);//非必須,給用戶端發送一個接受成功的回複 send data to connected System.Net.Sockets.Socket socket.Shutdown(SocketShutdown.Both);//(6)Disables sends and receives on a System.Net.Sockets.Socket socket.Close();//(7)關閉socket Connection,釋放所有已佔用資源,在死迴圈內繼續接受其他訊息 } listener.Close(); //Close System.Net.Sockets.Socket connection and release all associated resources. Console.Read(); } //用戶端的socket程式 建立一個main程式來運行發送程式 public void ClientSocket() { Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//(1)首先在伺服器端定義一個通訊端(socket),使用Tcp協議 IPHostEntry ipHost=Dns.Resolve("127.0.0.1"); IPAddress ipAddress=ipHost.AddressList[0]; IPEndPoint ipEndPoint=new IPEndPoint(ipAddress,2112); sender.Connect(ipEndPoint);//(2)其次設定該通訊端的連結IP,發送到指定IP地址的2112連接埠 string sendStr = "hello, the socket test!"; byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr+"[FINAL]"); sender.Send(sendBytes);//(3)發送資料位元流 byte[] receiveBytes=new byte[1024]; sender.Receive(receiveBytes);//(4)擷取伺服器的響應資料 Console.WriteLine("received from server: " + Encoding.ASCII.GetString(receiveBytes)); sender.Shutdown(SocketShutdown.Both);//(5)Disables sends and receives on a System.Net.Sockets.Socket sender.Close();//(6)關閉socket Connection,釋放所有已佔用資源 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.