C # Network programming (IV) Socket programming principles __ Programming

Source: Internet
Author: User
Brief

The main features of connection-oriented services (TCP) are:
-Data transmission must be established, maintained and released in three phases
-in the process of transmission, the group does not need to carry the destination host's address
-Good reliability, but the protocol is complex, communication efficiency is not high
Key Features for connectionless services (UDP):
-All phases of the connection are not required
-Each group must carry the complete destination host address, transmits independently in the system
-because there is no sequential control, the group of receivers may be disorderly, repetitive and missing
-High communication efficiency, but cannot ensure reliability the basic usage of the socket class is the creation of the socket class

The constructor prototype for the socket class is:

Public Socket (addressfamily addressfamily,sockettype sockettype,protocoltype protocoltype)

For regular IP traffic, addressfamily can only be used with AddressFamily, inetnetwork, sockettype parameter needs, and ProtocolType
how sockets are grouped

SocketType ProtocolType Description
Dgram Udp Non-connected communication
Stream Tcp Connection-oriented communication
Raw Icmp The communication based on ICMP protocol
Raw Raw Communication for simple IP packets

create an instance of a streaming socket

Socket socket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);

create instance of datagram socket

Socket socket = new socket (addressfamily.internetwork, Sockettype.dgram, PROTOCOLTYPE.UDP);

creating an instance of the original socket

Socket socket = new socket (addressfamily.internetwork, Sockettype.raw, protocoltype.icmp);

Note here to learn the common properties of the socket, through which you can set or get information Bind (EndPoint address)

For server programs, sockets must be bound to a local IP address or port, with a clear local Listen (int backlog)

This method is used only for connection-oriented server parties whose parameters indicate the number of connections the system waits for a user program to queue, that is, the queue length. The connection request in the queue is processed by the Accept method according to the first in-first out principle Accept ()

This method is used only for connection-oriented servers, and after entering the listening state, the program executes to the method in a paused state until a client requests a connection. Once a connection request is made, the method accepts the request and returns a new socket object that contains all the connection information that the client communicates. The socket that was originally created is still only responsible for listening, and electrophoresis accept method to accept new connection requests when needed.

Iphostentry localHost = Dns.gethostbyname (Dns.gethostname ());
IPEndPoint localEP = new IPEndPoint (localhost.addresslist[0],3456);

Socket mysocket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
Mysocket.bind (LOCALEP);
Mysocket.listen (a);
Socket newsocket = mysocket.accept ();
New actions for newly generated newsocket

At this point, the data can be transferred through the newly generated newsocket.
By modifying the above statements, you can implement duplicate services and concurrent services .

Concurrent Services:

for (;;) {
     Socket newsocket = mysocket.accept ();
     if (CreateThread ()) {
         mysocket.close ();
         Newsocket Operations
     }
     newsocket.close ();
 }

Duplicate service

for (;;) {
    Socket newsocket = mysocket.accept ();
    Newsocket Operation
    Newsocket.close ();
}
Connect (EndPoint remoteep)

This method is a client that is oriented to a connection call, actively sending a connection request to the server with its parameters to be combined with the IP and port of the server side. When Connect is invoked, the client socket blocks until the connection is established, and an exception is returned if the connection is unsuccessful
How to use:

IPAddress remotehost = Ipaddress.parse ("180.149.132.47");//Baidu's address
ipendpoint remoteep = new IPEndPoint (remotehost );
Set the type of socket socket
sock = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
Sock. Connect (remoteEP);

The IP address and port number specified in remoteEP must be the process information that the server side uses for listening, not the local node information for the client. Receive/send Method

In data transmission, streaming sockets use the Receive and send methods, while datagram sockets use the ReceiveFrom and SendTo methods. There are multiple overloads for both the accept and send methods for connection-oriented sockets and datagram socket calls. Shutdown (SocketShutdown How) and Close method

After the communication is complete, use shutdown to prevent sending and receiving on the socket, and then close the socket using the closing method
Parameter value of the Shutdown method

Take value Description
Socketshutdown.both Stop sending and accepting on sockets
Socketshutdown.receive Stops accepting data on a socket. If additional data is received, a RST signal is issued
Socketshutdown.send Stops sending data on a socket. If all buffer data is sent out, a fin signal is emitted
Sock. Shutdown (Socketshutdown.both);
Sock. Close ();
Simple application Example of socket

Server-side code, this program needs to start first

This method is the server side, used to receive, must first start the
socket socket = new socket (AddressFamily.InterNetwork, SocketType.Stream, PROTOCOLTYPE.TCP);

IPEndPoint myHost = new IPEndPoint (Ipaddress.parse ("192.168.43.81"), 2345);

Socket. Bind (myHost);
Socket. Listen (2345);

Socket Receivesocket = socket. Accept ();

byte[] data = new byte[1024];

Receivesocket.receive (data);
String str = System.Text.Encoding.Unicode.GetString (data);
data = System.Text.Encoding.Unicode.GetBytes ("A reply from Server");
Receivesocket.send (data);
Console.WriteLine ("Received data is: {0}, has sent a reply", str);
Socket. Close ();
Receivesocket.close ();
Console.readkey ();

This is the client code that needs to be started after

This is the client, after boot
ipendpoint serverhost = new IPEndPoint (Ipaddress.parse ("192.168.43.81"), 2345);
Socket socket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
Socket. Connect (serverhost);
byte[] data = new byte[1024];
data = System.Text.Encoding.Unicode.GetBytes ("Hello This is a example");
Send the
socket. Send (data);
Console.WriteLine ("Data has been sent, waiting to receive data");
Receive
socket. Receive (data);
String str = System.Text.Encoding.Unicode.GetString (data);
Console.WriteLine ("received data, {0}", str);
Close the
socket. Shutdown (Socketshutdown.both);
Socket. Close ();

End.

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.