C # Socket Series A simple to create a socket listener

Source: Internet
Author: User

The socket application scenario, in fast, stable, keeps long connected data transfer codes. HTTP is also encapsulated by the socket, based on the one-time request reply, and then the disconnected socket connection.

For example, our common game server, the current very fire of the internet of Things server, all need to open the socket server to listen to the real-time transmission of data.

So how do we implement the socket listener? Speaking of which, we need to know that the socket listener is divided into TCP and UDP two forms, but TCP is actually a UDP package, can be regarded as reliable UDP transmission, based on UDP directed transmission, received message reply sender received the message. such as authentication, to achieve TCP data transmission, so generally our TCP transmission relative to UDP a little slower.

Let's first create a TcpListener class for the TCP state of the socket

1  /// <summary>2     ///establishing a TCP communication monitoring service3     /// </summary>4     Internal classTcpListener5     {6         PrivateIPEndPoint _ip;7         PrivateSocket _listeners;8         Private volatile BOOLIsinit =false;9list<tsocketbase> sockets =NewList<tsocketbase>();Ten  One         /// <summary> A         ///Initializing the server -         /// </summary> -          PublicTcpListener (stringIP ="0.0.0.0",intPort =9527) the         { -Isinit =true; -IPEndPoint localEP =NewIPEndPoint (Ipaddress.parse (IP), port); -              This. _ip =localEP; +             Try -             { +Console.WriteLine (string. Format ("Listen Tcp, {0}:{1}", IP, Port)); A                  This. _listeners =Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); at                  This. _listeners.bind ( This. _ip); -                  This. _listeners.listen ( the); -SocketAsyncEventArgs Sea =NewSocketAsyncEventArgs (); -sea.completed + =NewEventhandler<socketasynceventargs> ( This. Acceptasync_async); -                  This. Acceptasync (SEA); -             } in             Catch(Exception ex) -             { to Console.WriteLine (ex); +                  This. Dispose (); -             } the         } *  $         Private voidAcceptasync (SocketAsyncEventArgs SAE)Panax Notoginseng         { -             if(Isinit) the             { +                 if(! This. _listeners.acceptasync (SAE)) A                 { theAcceptasync_async ( This, SAE); +                 } -             } $             Else $             { -                 if(SAE! =NULL) -                 { the SAE. Dispose (); -                 }Wuyi             } the         } -  Wu         Private voidAcceptasync_async (Objectsender, SocketAsyncEventArgs SAE) -         { About             if(SAE. SocketError = =socketerror.success) $             { -                 varSocket =NewTsocketclient (SAE. AcceptSocket); - sockets. ADD (socket); -Console.WriteLine ("Remote Socket localendpoint:"+ SAE. Acceptsocket.localendpoint +"Remoteendpoint:"+SAE. AcceptSocket.RemoteEndPoint.ToString ()); A             } +Sae. AcceptSocket =NULL; the             if(Isinit) -             { $                  This. _listeners.acceptasync (SAE); the             } the             Else{SAE. Dispose (); } the         } the  -         /// <summary> in         ///Freeing Resources the         /// </summary> the          Public voidDispose () About         { the             if(Isinit) the             { theIsinit =false; +                  This. Dispose (true); -Gc. SuppressFinalize ( This); the             }Bayi         } the         /// <summary> the         ///releasing the resources that are occupied -         /// </summary> -         /// <param name= "Flag1" ></param> the         protected Virtual voidDispose ([MarshalAs (UNMANAGEDTYPE.U1)]BOOLFlag1) the         { the             if(FLAG1) the             { -                 if(_listeners! =NULL) the                 { the                     Try the                     {94Console.WriteLine (string. Format ("Stop Listener Tcp, {0}:{1}", This. Ip. Address.tostring (), This. Ip. Port)); the _listeners.close (); the _listeners.dispose (); the                     }98                     Catch { } About                 } -             }101         }102 103         /// <summary>104         ///Get binding Endpoint the         /// </summary>106          PublicIPEndPoint IP {Get{return  This. _ip;} }107}

The main two points of our socket initialization code are the new socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp), and the type of initialization is TCP based.

There is our binding IP address, the past many people socket bind address used to write 127.0.0.1 (test environment) or read network card information, read IP address, so troublesome, code to write a lot, cut does not conform to multi-network card multi-line actual environment. We use 0.0.0.0 to indicate all line monitoring on IPv4, including your multi-channel NIC, and 127.0.0.1

1     class  Program 2     {3         staticvoid Main (string[] args)4          {5             new  TcpListener (); 6             console.readline (); 7         }8     }

Let's run a look at the effect

Next we'll use Telnet to test

Turn on Telnet

Then open cmd

Enter Telnet 127.0.0.1 9527

We see that a connection was received

C # Socket Series A simple to create a socket listener

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.