C # TCP application programming two simultaneous TCP Application Programming

  No matter how complex TCP applications, both the basic premise is to communicate the client and server side first TCP connection before you can send and receive data with each other on this basis. Because the server needs to service multiple clients simultaneously, so the program is relatively complicated. On the server side, programmers need to write programs continue to monitor whether the client connection request, and through the socket distinguish which client; and the client and the server connection is relatively simple, only need to specify which server to connect. Once the two sides established a connection and create a corresponding socket, you can send and receive data each other up. In the program, the method of transmitting and receiving data are the same, the difference is only in different directions.

  In synchronous TCP application programming, send, receive and monitor the use of statements are blocking the way to work. The general steps using simultaneous TCP write server-side program is:

1) Create a network type, data transmission type and protocol type comprises a local socket object used, the IP address and port number of the server and its binding. This process can be completed through the Socket class or classes TcpListener.
2) listen on the specified port, connected to receive the client requests.
3) Upon acceptance of the connection request from the client, corresponding to the created client TcpClient Socket object or objects according to the connection information sent by the client.
4) Socket according TcpClient object or objects created, each data transmission connection with each client.
5) determining whether to close the connection information with each other according to transmission conditions.
General Procedure using TCP synchronization of writing the client:
1) Create a network type, data transmission type and protocol type TcpClient Socket object or objects used during transmission comprising a.
2) Connect method to establish a connection with the remote server.
3) for data transmission to the server.
4) After completion of the work, transmits information to the server off and close the connection to the server.
To give the reader an idea of TcpClient and TcpListener difference after socket programming and packaging, here we are on the three key codes implemented in the program to make a brief introduction.

1 to send and receive data using sockets

  In the network, the data is a stream of bytes for transmission. After the data conversion server and the client to establish a connection both ends, the program first needs to be transmitted is a byte array, and then transmits data using the Socket object Send method, or receive data using the Receive method. Note that the array of bytes to be sent is not sent directly to the remote host, but this machine is sent to the TCP transmission buffer; the same token, the reception data is true, i.e., the program data is received from the TCP receiving buffer. SendBufferSize property can be used to get or set the Socket class transmission buffer size, using ReceiveBufferSize property Gets or sets the receive buffer size, its default size may be used. As for when the system will buffer the data sent over the network to a remote host, which factors influence the subject, there is no need to consider in the program.

1.1 server-side programming key codes

  In the server side programs, the key code for send and receive data using a socket:

using System.Net;
using System.Net.Sockets;
……
IP ipadress = IPAdress.Prase ( " server IP address " );
IEP the IPEndPoint = new new the IPEndPoint (IP, available port number);
Socket socket = new Socket(AdressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(iep);
socket.Listen (the maximum number of client connections);
Socket clientSocket = socket.Accept();
……
// send data to the client by the clientSocket, 
String Message = " data transmission " ;
 byte [] = sendbytes System.Text.Encoding.UTF8.GetBytes (Message);
 int successSendBytes = clientSocket.Send (sendbytes, sendbytes.Length, SocketFlags .None);
……
// By clientSocket receiving the data sent by the client 
byte [] = receivebytes new new  byte [ 1024 ];
 int successReceiveBytes = clientSocket.Receive (receivebytes);

  Because TCP is connection-oriented protocol, so before sending the data, the program should first socket to this IP address and port number binding, make it in a listening state, and if there Accept method by listening client connection requests . Sockets are used to indicate which protocol is used; and the native binding to listen on the specified port, the connection information to identify the client; Accept object method call it is to obtain each other's IP address and port number of sets of contact information word need. Because the only other side to get information about the IP address and port number to communicate with each other. When the program executes the Accept method, it will be in the blocked state until a client to server connection request before continuing to the next statement. Upon acceptance server connected to the client, Accept method returns a socket included in each other's IP address and port number with the new client communication socket, then the socket can be used and returned the client communicates a.

  Integer Send method returns a value indicating the number of bytes successfully transmitted. As we mentioned at the beginning of this section as data which is not to be sent immediately transferred to the network, but transferred to the TCP send buffer. However, in blocking mode, if the original cause of data due to network TCP send buffer has not had time to send over the network, the recipient will not be able to continue to receive all of its number of bytes sent, this method actually returns success how many bytes were sent to the TCP send buffer.

  If not because the network reasons, we can not guarantee that the data will be able to once and for all delivered to the TCP send buffer. This is because the TCP send buffer can receive data again depends on the size of its own, that is, data Send method to send exceeds the effective value of the TCP send buffer, then the method will not be able to call a Send all data successfully sent to the cache. Therefore, the actual programming, the program should be sent through a loop, and detects the number of bytes successfully transmitted, until all the data successfully sent. Of course, if the data sent Send method is less than the effective value of the TCP send buffer, called once Send method could all sent successfully.

  In contrast to the transmission, the Receive method is to receive data from the TCP receiving buffer, the Receive method returns an integer number of bytes actually received value represents, but if the remote client socket connection is closed, but this time the valid data has been is completely received, the Receive method will return value is 0 bytes.

  But one thing to note that if there is no valid data received TCP readable buffer, in blocking mode, the Receive method will be blocked; but in non-blocking mode, the Receive method will end immediately and throw sleeved word exception. To avoid this, we can use the property Available advance to detect whether data is valid, if the Available attribute value is not 0, then the receiving operation be retried.

1.2 Client Programming key codes

  For the client, only you need to create the IP address and port number of the server and the server connection, once the connection is successful, you can transmit data to each other through a socket with the server, the key code:

IP = IPAddress.Parse the IPAddress ( " server IP address " );
IEP the IPEndPoint = new new the IPEndPoint (IP, server listening port number);
Socket serverSocket=new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
serverSocket.Connect(iep);
……
// send data to the server via serverSocket 
String Message = " data transmission " ;
 byte [] = sendbytes System.Text.Encoding.UTF8.GetBytes (Message);
 int successSendBytes = serverSocket.Send (sendbytes, sendbytes.Length, SocketFlags. none);
……
// sent by the receiving server serverSocket data 
byte [] = receivebytes new new  byte [ 1024 ];
 int successReceiveBytes = serverSocket.Receive (receivebytes);

  Visible, the client program, a method similar to the method of transmitting and receiving data send and receive data and server-side use different sockets difference is created.

2 transmit and receive data using objects NetworkStream

  NetworkStream dedicated network objects to process the stream data. After creating the NetworkStream object, the object data can be transmitted and received directly. E.g:

NetworkStream networkStream = new NetworkStream(clientSocket);
……
// send data 
String Message = " data transmission " ;
 byte [] = sendbytes System.Text.Encoding.UTF8.GetBytes (Message);
networkStream.Write(sendbytes,0, sendbytes.Length );
……
//接收数据
byte[] readbytes = new byte[1024];
int i = networkStream.Read(readbytes, 0, readbytes.Length);

  Send method with different sockets, the Write method NetworkStream object void return value, why it does not return the number of bytes actually transmitted, because all the Write method ensures data byte array to the TCP send buffer , avoiding the problems encountered when calling the send method using the Socket class may not be able to send data once all sent successfully simplifies the programming effort to a certain extent. But all this must be operating for the job when Writeable property values ​​NetworkStream valid object, so before using the Write method NetworkStream object to be detected Writeable property NetworkStream object is to True.

  If a single line of text is transmitted all the information to create an object NetworkStream after use ReadLine and WriteLine method StreamReader class and the StreamWriter class simpler, and does not need to be programmed to convert between the strings and arrays.

  Write method and corresponds to call Read method NetworkStream class attribute value before CanRead ensure effective NetworkStream object. In this context, the process once all the valid data in the receiving buffer is read into variable, and returns the number of bytes successfully read.

  Note that, the reason why the Read method also has an integer return value, since it is possible TCP receiving buffer has not received the data transmitted over the designated length of the other side. In other words, the received data may not be that many. In the following pages, we will further study methods to solve this problem.

  Read in process, and that a similar method Receive Socket class, i.e., if the remote host closed socket connection, and at this time the valid data has been completely received, then the return value of Read byte will be zero.

And Class 3 TcpClient TcpListener

  In System.Net.Sockets Namespace, TcpClient class and two classes TcpListener class is dedicated to programming TCP protocol. Both class encapsulates the underlying socket, respectively, and provide synchronous and asynchronous operation of the method of encapsulating Socket, TCP applications to reduce the difficulty of programming.

  TcpClient class for connecting, transmitting and receiving data, whether the class The TcpListener listening for incoming connection requests.

3.1 TcpClient class

  TcpClient class classified under System.Net namespace. TcpClient class using the methods provided, may be connected through the network, send and receive network traffic. There are four class constructor overloads:

  1) TcpClient ()
  The default constructor creates a TcpClient object, which automatically selects the client unused IP address and port number. After the object is created to make the connection with the server using the Connect method. E.g:

TcpClient tcpClient=new TcpClient();
tcpClient.Connect("www.abcd.com", 51888);

  2) the TcpClient (AddressFamily Family)
  the TcpClient constructor creates an object that can also automatically select the IP address and port number of the client has not been used, but the use of AddressFamily enumeration specifies which network protocol to use. After the object is created to make the connection with the server using the Connect method. E.g:

TcpClient tcpClient = new TcpClient(AddressFamily.InterNetwork);
tcpClient.Connect("www.abcd.com", 51888);

  . 3) the TcpClient (IPEndPoint IEP)
  IEP IPEndPoint object type, iep specifies the IP address and port number of the client. When the client host has more than one IP address, this constructor may be used to select the IP address of the client host to be used. E.g:

IPAddress[] address = Dns.GetHostAddresses(Dns.GetHostName());
IPEndPoint iep = new IPEndPoint(address[0], 51888);
TcpClient tcpClient = new TcpClient(iep);
tcpClient.Connect("www.abcd.com", 51888);

  4) TcpClient (string hostname, int port)
  This is the most convenient to use a configuration function. This configuration function may directly designate the domain name and port number of the server, but without using the connect method. Client host IP address and port number is automatically selected. E.g:

TcpClient tcpClient=new TcpClient("www.abcd.com", 51888);

  Tables 1 and 2 list the common TcpClient class attributes and methods.

    Table 1 TcpClient class common properties

Attributes meaning
Client Gets or sets the underlying socket
LingerState Gets or sets remains connected to the socket
NoDelay Gets or sets a value that disables delay when sending or receiving buffer is not full
ReceiveBufferSize Gets or sets the size of the receive buffer Tcp
ReceiveTimeout Gets or sets the socket receive data timeout
SendBufferSize Gets or sets the transmit buffer size Tcp
SendTimeout Gets or sets the transmission data socket timeout

    Table 2 TcpClient class conventional method

method meaning
Close Release TcpClient example, without closing the underlying connection
Connect With the specified host name and port number to connect the client to the TCP host
start Connect Asynchronous request to start a remote host connection
EndConnect Asynchronous accepts an incoming connection attempt
GetStream Get NetworkStream objects capable of transmitting and receiving data

3.2 TcpListener class

TcpListener class and listening for incoming connection requests received. The constructor of the class are:

  1) TcpListener (IPEndPoint iep)
  wherein iep IPEndPoint object type, iep contains IP address and port number of the server. The constructor connection request at the specified IP address and port objects by listening client IPEndPoint type.

  2) TcpListener (IPAddress localAddr, int port)
  to establish a TcpListener object specifying local IP address and port directly in the parameter, and by specifying the local IP address and port number to listen for incoming connection requests.

  After TcpListener constructed object, you can monitor the client connection request. And similar TcpClient, The TcpListener provided respectively synchronous and asynchronous methods, in the synchronous mode of operation, there is a corresponding method AcceptTcpClient, AcceptSocket method, the Start and Stop methods methods.

  AcceptSocket method for obtaining the object and returns a socket for receiving and transmitting data in a synchronous blocking mode. The socket comprises an IP address and port number of the local and remote host, and communicating by calling the object's Send and Receive Socket method and the remote host.
  AcceptTcpClient a method for obtaining and returning the package can be used to receive and transmit data to the Socket TcpClient object blocking synchronous mode.

  Start method used to start the listener, constructors are:

public void Start(int backlog)

  Maximum integer parameter request backlog queue length, i.e. maximum allowed number of client connections. After the Start method is called, and his own LocalEndPoint underlying Socket object to bind together, and Listen Socket object method is called automatically start listening for requests from clients. If you accept a client request, Start method will automatically put the request into the request queue, and then continue to monitor the next request until you call the Stop method to stop listening. When the maximum length of the received request exceeds TcpListener request queue is 0 or less, awaits a connection request to the remote host will throw an exception.

  Stop method to stop listening for requests constructor:

public void Stop()

  Stop the program execution method, immediately stop listening client connection requests, and close the object underlying Socket. Waiting requests in the queue will be lost, waiting to accept a connection request of the remote host will throw an exception socket.

4 No TCP protocol messaging solution of the border issue

  While using TCP communication protocol, the receiver is able to receive data in the order sent by the sender, but the transmission in the network, may be inconsistent sender transmits a message with the recipient of a message received phenomenon. For example: the first character string data sender for sending "12345", the second character string data to be transmitted is "ABCDE"; Normally, the recipient receives the first received character string should be: "12345" , received a second time: "abcde".

  However, when the transceiver the information is very fast, the receiving party might last received content is "12345abcde", i.e. with two or receiving content transmitted multiple times.

  There is also a most extreme case is that the recipient may go through several times to receipt of a message sent by the sender. E.g. first receipt of "1234", the second as "45AB", the third as "CDE."

  This is mainly because the TCP protocol is byte-stream format, no protocol message boundaries, due to uncertainties in the transmission network, and therefore can not guarantee that the individual data are read Send method of transmitting a single Receive method.

  If you need to parse the command sent by the sender, in order to ensure that the receiver does not resolve the error occurs, the message must be considered when programming the border issue, otherwise it may appear lost commands incorrect results. For example, the case of a message sent twice received all at once, although the received content and no less, but if every time a command is received are considered in the program, you will lose another command, resulting in a logical error. Like network chess program, lost a step, the entire logic on all hell broke loose.

  The method of practical application, the TCP protocol message boundaries to solve the problem in three ways:

  1) The first method is a fixed length message. This method is applicable to the case of a fixed length message.

  In specific implementation, the objects may be named BinaryReader System.IO space by a fixed-length transmission data for each stream to the network, for example, each transmission of a 32-bit integer type int. BinaryReader BinaryWriter objects and provides a variety of methods overloaded, transmitting and receiving data having a fixed length type is very convenient.

  2) The second method is to send the message along with the message length. For example the machine in front of each transmitted message 4 bytes indicating the length of this message, then the message will contain the message length is sent to the remote host; remote host after receiving the message, the first message from the first four bytes obtaining a message length, then the received message data are cyclically sent by the sender according to the message length value. This method can be applied to any occasion.

  BinaryReader BinaryWriter objects and objects is also the most convenient way to achieve this approach. BinaryWriter object provides a number of overloaded Write method can be applied to any occasion. For example, when writing a string to a web, the method automatically calculates the number of bytes occupied by the character string, and the string of 4 bytes as prefix attached in front of the string; recipient using the method of receiving character ReadString when the string, it first reads the string prefix and the prefix automatically read character string character string specified length.

  If the binary stream data, such as binary files using the TCP protocol is transmitted over the network, you need to implement the function calculated by the code length of the program. Examples of network data encryption and decryption book chapter, transfer encrypted data over a network to solve the border issue is the use of this method.

  3) A third method is to use a special marker message separator. For example CRLF (\ r \ n) as a delimiter. This method is mainly used in case the message does not contain the special flag.

  For string processing, the most convenient way to achieve this is by StreamWriter object and StreamReader object. Per sender StreamWriter object WriteLine method sends a string of write network flow, the recipient per ReadLine method only use the StreamReader object with a carriage return line feed stream from the network that is read out as a string tag can. Examples in this chapter are using this method.

  Three ways to deal with message boundaries of their advantages and disadvantages, can not say what is good in what way bad way. One suitable method should be selected according to actual conditions during programming.

Guess you like

Origin www.cnblogs.com/wintertone/p/11649702.html