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 for the tcp status of the socket.
1 /// <summary> 2 // establish 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 IP EndPoint (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 SocketAsyncEventArgs (); 26 sea. completed + = new EventHa Ndler <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}
The initialization code of the socket is new Socket (AddressFamily. InterNetwork, SocketType. Stream, 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 }
Let's take a look at the effect.
Next we will test it using telnet.
Enable telnet
Then open cmd
Enter telnet 127.0.0.1 9527
We can see that we have received a connection.