C # basic Socket Communication Knowledge

Source: Internet
Author: User

I recently started to study Socket programming. Today, I have sorted out the basic knowledge of Socket programming to facilitate recording and digestion. The content is relatively basic, but I think Socket programming is still very important, so I did a simple research.

Some things have not been understood yet, so I have to learn and summarize them. I hope everyone will like them!

I. IP address operations

1. IPAddress class

A. There is a Parse () method in this class. You can convert the decimal IP representation of the vertex into an IPAddress class. The method is as follows:

IPAddress address = IPAddress. Parse ("192.168.0.1 ");

B. IPAddress provides four read-only fields.

Any is used to represent Any IP addresses available in the local system.

Broadcase is used to represent the IP broadcast address of the local network.

Loopback is used to represent the system's return address.

None indicates that there is no network interface on the system.

IPAddress. Any is commonly used to represent all IP addresses on the local machine. This is the most convenient way to listen for the socket service, so you do not need to listen for each IP address.

IPAddress. Broadcase can be used to broadcast udp ip addresses. These are detailed in socket.

2. IPEndPoint class

We can create an IPEndPoint class using two constructor methods:

A. IPEndPoint (long address, int port)

B. IPEndPoint (IPAddress address, int port)

Four attributes: Address, AddressFamily, Port, MaxPort, and MinPort

These should be well understood in terms of names and will not be described one by one. IPEndPoint is actually the binding of an IP address and port, which can represent a service for Socket communication.

Ii. DNS-related categories

The DNS class has four static methods to obtain host DNS information,

1. GetHostName ()

You can use Dns. GetHostName () to obtain the Host Name of the local computer.

2. GetHostByName ()

An IPHostEntry object is returned Based on the host name:

IPHostEntry GetHostByName (string hostName)

IPHostEntry associates a DNS host name with an array of individual names and IP addresses. It has three attributes: AddressList: an array of IPAddress objects, Aliases: an array of string objects, and HostName: A String object used for the host name


3. GetHostByAddress ()

Similar to GetHostByName (), but the parameter here is an IP address, rather than a host name, it also returns an IPHostEntry object.

IPHostEntry GetHostByAddress (IPAddress address)

IPHostEntry GetHostByAddress (string address)

4. Resolve ()

When we do not know the format of the input remote host address (host name or IP address), we can use the above two methods to determine the format entered by the customer, can be used correctly, but the Dns class provides

A simpler method, Resolve (), which can accept any address in the Host Name format or IP address format and return the IPHostEntry object.

Iii. Socket programming

For Socket programming, we usually follow the steps below:

A. Server

1. Create an IPEndPoint instance for binding when the Socket listens

IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 6001);

2. Create a socket instance

mServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

3. Bind the socket and IPEndPoint

mServerSocket.Bind(ipep);

4. Set the socket to the listening mode.

mServerSocket.Listen(10);
5. Receive client connections and enable a thread to receive data

While (true) {try {mClientSocket = mServerSocket. accept (); mClientThread = new Thread (ReceiveData); mClientThread. start ();} catch (Exception e) {Console. writeLine ("Socket communication Exception error:" + e. message );}}
The ReceiveData () method for receiving data is defined as follows:

////// Method for receiving client data //////
 Private static void ReceiveData () {bool keepActive = true; // client Socket mSocket = mClientSocket; // buffer size Byte [] buffer = new Byte [1024]; // obtain the client information IPEndPoint Clientipep = (IPEndPoint) mClientSocket. remoteEndPoint; // output client information Console. writeLine ("[system]: client" + Clientipep. address + ":" + Clientipep. port + "Join connection"); // wait for the client to respond while (keepActive) {try {// obtain the data size mLength = mSocket. available; // accept data mSocket. receive (buffer, 0, mLength, SocketFlags. none); // determine whether the data has been read. if (mLength = 0) continue;} catch (Exception e) {Console. writeLine ("an exception occurred when reading data:" + e. message);} // output client Message Console. writeLine ("[client]:" + Encoding. unicode. getString (buffer ). toString ());

The code for sending data is as follows:

// Send data byte [] data = new byte [1024] to the client; data = Encoding. Unicode. GetBytes ("received by the server! "); MSocket. Send (data, data. Length, SocketFlags. None );

B. Client

Similar to the server, the following code is provided:

IPEndPoint ipep = new IPEndPoint (IPAddress. parse ("127.0.0.1"), 6001); mClientSocket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); try {mClientSocket. connect (ipep); if (mClientSocket. connected) {Console. writeLine ("[system]: The client has been connected to the server and starts to send data to the server"); Console. writeLine ("[client]: I am a client" + ipep. address + ":" + ipep. port + "I am sending data to the server"); // send data to the server byte [] data = new byte [1024]; data = Encoding. unicode. getBytes ("Hello, server, I am a client"); mClientSocket. send (data, data. length, SocketFlags. none); // prompt the user to wait for the server to respond to the Console. writeLine ("[system]: Wait for the server to respond ...... "); while (true) {mLength = 0; try {mLength = mClientSocket. available; mClientSocket. receive (mData, mLength, SocketFlags. none); if (mLength = 0) continue;} catch (Exception e) {Console. write ("failed to read server data:" + e. message); return;} Console. writeLine ("[server]:" + Encoding. unicode. getString (mData ). substring (0, mLength ). toString () ;}} catch (Exception e) {Console. writeLine ("failed to connect to the server:" + e. message); return ;}


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.