C # Socket Series 1 simple socket listener Creation

Source: Internet
Author: User

C # Socket Series 1 simple socket listener Creation
The socket Application Scenario is fast, stable, and maintains persistent connection data transmission code. Http is also encapsulated by socket. It is encapsulated based on the socket connection that is closed after one request is responded. For example, for common game servers, the currently popular Iot servers, all need to enable socket servers to listen for real-time data transmission. So how can we implement socket listening. Speaking of this, we need to know that the socket listener is divided into two forms: tcp and udp. However, tcp is actually encapsulated by udp, which can be seen as reliable udp transmission and udp-based targeted transmission, the sender receives the message. To implement tcp data transmission, so tcp transmission is generally a little slower than udp. We will first create a TCPListener class 1 // <summary> 2 // establish the tcp communication listening service 3 // </summary> 4 internal class TCPListener 5 {6 private IPEndPoint _ IP; 7 private Socket _ Listeners; 8 private volatile bool IsInit = false; 9 List <TSocketBase> sockets = new List <TSocketBase> (); 10 11 /// <summary> 12 // initialize server 13 /// </summary> 14 public TCPListener (string ip = "0.0.0.0", int port = 9527) 15 {16 IsInit = True; 17 IPEndPoint localEP = new IPEndPoint (IPAddress. parse (ip), port); 18 this. _ IP = localEP; 19 try 20 {21 Console. writeLine (string. format ("Listen Tcp-> {0 }:{ 1}", ip, port); 22 this. _ Listeners = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); 23 this. _ Listeners. bind (this. _ IP); 24 this. _ Listeners. listen (5000); 25 SocketAsyncEventArgs sea = new SocketAsyncEventAr Gs (); 26 sea. completed + = new EventHandler <SocketAsyncEventArgs> (this. acceptAsync_Async); 27 this. acceptAsync (sea); 28} 29 catch (Exception ex) 30 {31 Console. writeLine (ex); 32 this. dispose (); 33} 34} 35 36 private void AcceptAsync (SocketAsyncEventArgs sae) 37 {38 if (IsInit) 39 {40 if (! This. _ Listeners. AcceptAsync (sae) 41 {42 AcceptAsync_Async (this, sae); 43} 44} 45 else 46 {47 if (sae! = Null) 48 {49 sae. dispose (); 50} 51} 52} 53 54 private void AcceptAsync_Async (object sender, SocketAsyncEventArgs sae) 55 {56 if (sae. socketError = SocketError. success) 57 {58 var socket = new TSocketClient (sae. acceptSocket); 59 sockets. add (socket); 60 Console. writeLine ("Remote Socket LocalEndPoint:" + sae. acceptSocket. localEndPoint + "RemoteEndPoint:" + sae. acceptSocket. remoteEndPoint. toS Tring (); 61} 62 sae. acceptSocket = null; 63 if (IsInit) 64 {65 this. _ Listeners. acceptAsync (sae); 66} 67 else {sae. dispose ();} 68} 69 70 // <summary> 71 // release resource 72 /// </summary> 73 public void Dispose () 74 {75 if (IsInit) 76 {77 IsInit = false; 78 this. dispose (true); 79 GC. suppressFinalize (this ); 80} 81} 82 // <summary> 83 // release the occupied resources 84 // </summary> 85 // <param name = "flag1"> </p Aram> 86 protected virtual void Dispose ([financialas (UnmanagedType. U1)] bool flag1) 87 {88 if (flag1) 89 {90 if (_ Listeners! = Null) 91 {92 try 93 {94 Console. writeLine (string. format ("Stop Listener Tcp-> {0 }:{ 1}", this. IP. address. toString (), this. IP. port); 95 _ Listeners. close (); 96 _ Listeners. dispose (); 97} 98 catch {} 99} 100} 101 102 103 // <summary> 104 // get the bound endpoint 105 // </summary> 106 public IPEndPoint IP {get {return this. _ IP ;}} 107} two main points: the socket initialization Code new Socket (AddressFamily. interNetwork, SocketType. st Ream, ProtocolType. Tcp); the initialization type is based on tcp. In addition, we bound the IP address. In the past, many people used to write the bind Address of the socket as 127.0.0.1 (test environment) or read the NIC information and read the IP address. This is troublesome and requires a lot of code writing, switch does not match the actual environment of multiple NICs and multiple lines. We use 0.0.0.0 to enable all ipv4 line listening, including your nic and 127.0.0.1 1 class Program2 {3 static void Main (string [] args) 4 {5 TCPListener tcp = new TCPListener (); 6 Console. readLine (); 7} 8}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.