Socket network communication in Dotnet

Source: Internet
Author: User

This article introduces the basic knowledge of Socket. 

The TCP protocol can provide interfaces for upper-layer networks, so that data transmission over the upper-Layer Networks is established on a "non-differentiated" network. To establish a TCP connection, you must go through the "three-way handshake". For details, see "Computer Network".

SOCKET is an implementation of TCP/IP network communication. Five types of information required for network communication:

Protocol used for connection (TCP/UDP)

IP address of the local host

Protocol port of the local Process

IP address of the remote host

Protocol port of Remote Process

Through SOCKET, you can establish a SOCKET connection through concurrent links in the application. One of the sockets is run on the client, called ClientSocket, and the other is run on the server, called ServerSocket.

 

Socket connection process: 

The connection process between sockets is divided into three steps: server listening, client requests, and connection confirmation.

Server listening: the server socket does not locate the specific client socket, but is waiting for connection. It monitors the network in real time and waits for client connection requests.

Client request: the client socket initiates a connection request, pointing out the address and port number of the server socket, and then sending a connection request to the server socket.

Connection Confirmation: when the server socket monitors or receives a connection request from the client socket, it responds to the request from the client socket and establishes a new thread for connection, the server socket continues to be in the listening status, and continues to receive connection requests from other client sockets.

 

When creating a Socket connection, you can specify the transport layer protocol used. The Socket can support different transport layer protocols (TCP or UDP). When using the TCP protocol for connection, this Socket connection is a TCP connection, also known as a stream Socket. When UDP is used for connection, the Socket connection is a UDP connection, also known as a datagram Socket.

 

What is Socket?

The Socket can be seen as two interfaces located on the client and server in the Communication Connection of the program. One program writes a piece of information into the Socket, and the Socket sends this information to another Socket, this information can be transmitted to other programs. A Socket is an abstraction layer through which an application sends and receives data, just as an application opens a file handle and reads and writes data to a stable storage. You can use Socket to add applications to the network and communicate with other applications in the same network. The information written by applications on one computer to the socket can be read by another application on the other computer. Based on different underlying protocols, there are also many different sockets. This blog post only covers the TCP/IP protocol family. The main Socket types in this protocol family are stream socket and datagrams socket ). Stream socket uses TCP as its peer protocol and provides a reliable byte stream service. The datagram socket uses the UDP protocol to provide a "best effort" datagram service, through which an application can send up to 65500 bytes of personal information.

 

About Socket classes in DotNet:

. NetFrameWork provides the System. Net. Socket namespace for Socket communication. The namespace contains the following important classes:

· The Socket class is a low-level class used internally to manage connections, WebRequest, TcpClient, and UdpClient.

· The NetworkStream class is derived from Stream, which indicates data streams from the network.

· TcpClient class allows you to create and use TCP connections

· TcpListener class allows listening for incoming TCP connection requests

· UdpClient class is used to create connections for UDP clients (UDP is another TCP protocol, but it is not widely used and is mainly used for local networks)

C # code

  1. Socket (AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType );

The addressFamily parameter specifies the addressing scheme used by the Socket, The socketType parameter specifies the Socket type, and the protocolType parameter specifies the protocol used by the Socket.

Server:

1. Create a Socket instance

C # code
  1. Socket s = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );

2. Bind the Socket instance to a port on the server (Local Machine)

C # code
  1. IPAddress ip = IPAddress. Parse ("172.16.1.15 ");
  2. IPEndPoint ipe = new IPEndPoint (ip, 2000 );
  3. S. Bind (ipe); // Bind port 2000

3. Start listening. If the listening is successful, process it accordingly.

Client:

 

C # code
  1. While (true)
  2. {
  3. S. Listen (0); // start listening
  4. Socket temp = s. Accept (); // create a new Socket for the new connection.
  5. String recvStr = "";
  6. Byte [] recvBytes = new byte [1, 1024];
  7. Int bytes;
  8. Bytes = temp. Receive (recvBytes, recvBytes. Length, 0); // Receive information from the client
  9. RecvStr + = Encoding. ASCII. GetString (recvBytes, 0, bytes );
  10. Console. WriteLine ("Server Get Message: {0}", recvStr); // display information sent from the client
  11. String sendStr = "From server: OK! Client Send Message Sucessful! ";
  12. Byte [] bs = Encoding. ASCII. GetBytes (sendStr );
  13. Temp. Send (bs, bs. Length, 0); // return the client success message
  14. Temp. Close ();
  15. }

 

1. Create a Socket instance

C # code
  1. Socket s = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );

2. Connect the Socket to the server

C # code
  1. IPAddress ip = IPAddress. Parse ("172.16.1.15 ");
  2. IPEndPoint ipe = new IPEndPoint (ip, 2000); // convert the ip address and port to an IPEndPoint instance
  3. C. Connect (ipe); // Connect to the server

3. send information to the server

C # code
  1. String sendStr = "hello! This is a socket test ";
  2. Byte [] bs = Encoding. ASCII. GetBytes (sendStr );
  3. C. Send (bs, bs. Length, 0); // Send test information

4. receive the information returned by the server

C # code
  1. String recvStr = "";
  2. Byte [] recvBytes = new byte [1, 1024];
  3. Int bytes;
  4. Bytes = c. Receive (recvBytes, recvBytes. Length, 0); // The slave server accepts the returned information.
  5. RecvStr + = Encoding. ASCII. GetString (recvBytes, 0, bytes );
  6. Console. WriteLine ("Client Get Message: {0}", recvStr); // display the Server Response Information

5. Disable Socket

   

C # code
  • C. Close ();
  • 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.