C # socket program (TCP)

Source: Internet
Author: User

In fact, as long as the socket connection is used, thread is basically used, which is cross-used.
C # encapsulation socket usage is basically not very complicated, but I don't know whether the hosted socket has any other performance or security issues.
The underlying operation that can be found in C # Is socket. The concept is not explained.
ProgramThe model is as follows:
Winform program: starts port listening, monitors socket connections, and regularly closes inactive connections;
Listener: process the socket's accept function, listen for new connections, and create a new thread to process these connections ).
Connection: processes the session of each connection.

1: How does winform start a new thread to start listener:
// Start the server
Private void btn_startserver_click (Object sender, eventargs E)
{
// This. btn_startserver.enabled = false;
Thread _ createserver = new thread (New threadstart (waitforconnect ));
_ Createserver. Start ();
}
// Wait all connections
Private void waitforconnect ()
{
Socketlistener listener = new socketlistener(convert.toint32(this.txt _ port. Text ));
Listener. startlistening ();
}
Because the listener connection is a function that waits cyclically, it cannot be directly executed in the winform thread. Otherwise, winform cannot continue any operations, so a new thread is specified to execute this function and start the listener loop.
This new thread is relatively simple. Basically there is no startup parameter, and you can simply specify the processing function.
2: How does listener start loop listening and start a new thread with parameters to process socket connection sessions.
First, let's look at how to establish a listener: (startlistening function)
Ipendpoint localendpoint = new ipendpoint (_ IPaddress, _ port );
// Create a TCP/IP socket.
Socket listener = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
// Bind the socket to the local endpoint and listen for incoming connections.
Try
{
Listener. BIND (localendpoint );
Listener. Listen (20); // 20 trucks

// Start listening for connections.
While (true)
{
// Here will be susponded while waiting for a new connection.
Socket Connection = listener. Accept ();
Logger. Log ("Connect", connection. remoteendpoint. tostring (); // log it, new connection
......
}
}......
The basic steps are relatively simple:
Create an ipendpoint object for the local machine to listen on the specified port;
Then bind it to a listening socket;
Enter the while loop and wait for a new join;
If a new connection exists, create a new socket to correspond to the session of the connection.
It is worth noting that this sentence is connected. Code : Listener. Accept (). When this sentence is executed, the program waits here until there is a new joint inspection request. This is synchronous execution. Of course, it can also be executed asynchronously.

The new connection socket is established (after accept). What should I do with these new sockets? They are still a loop wait, so we still need to create a new thread to Process sessions (receive/send messages) for these sockets, and this thread will receive parameters.
Thread itself cannot receive parameters. To enable it to receive parameters, you can define a new class and add parameters as attributes.
Because each socket is a connection cycle, I have defined such a class public class connection. This class has at least one such constructor public connection (Socket socket). The reason for this is to pass the socket parameter to the connection object so that the listener can start this thread, thread can know which socket he is processing.
Specific solution: (in the startlistening function of listener, ocket connection = listener. Accept)
Connection gpscn = new connection (connection );
// Each socket will be wait for data. Keep the connection.
Thread thread = new thread (New threadstart (gpscn. waitforsenddata ));
Thread. Name = connection. remoteendpoint. tostring ();
Thread. Start ();
In this way, the new socket runs in the new thread after the accept.
3: Connection session Processing
After a new connection (socket) is established, the remote connection can be connected to the socket, which is nothing more than send and receive.
Now let's take a look at how to write the connection. waitforsenddata function run by this thread.
While (true)
{
Bytes = new byte [1024];
String data = "";
// Wait m will be waiting the MSG of receive envet. Like accept ();
// Here will be susponded while waiting for socket income MSG.
Int bytesrec = This. _ connection. Receive (bytes );
_ Lastconnecttime = datetime. now;
If (bytesrec = 0) // close envent
{
Logger. Log ("close connection", _ connection. remoteendpoint. tostring ());
Break;
}
Data + = encoding. ASCII. getstring (bytes, 0, bytesrec );
//....... Handle your data.
}
The basic process is as follows:
Execute the receive function to receive messages sent from remote sockets;
Converts information from byte to string;
Process the information and enter the next loop. Wait until the socket sends new information.
Note the following:
1: receive function. This function is similar to the accept function of listener. Wait for execution in this place. If there is no new message, this function will not execute the next sentence and will remain waiting.
2: receives byte streams and needs to be converted to strings.
3: Determine how to remotely close the connection
4: If the message of the other party is very large, the data must be received cyclically.
4: How to manage these connections (threads)
Through the above program, you can basically establish a listener and process the connection session. But how to manage these threads? Otherwise, thread generation is a disaster.
The management method is relatively simple. In listener, I defined a static hash table (static public hashtable connections = new hashtable ();) to store the connection instance and its corresponding thread instance. A definition of the last join time (Private datetime _ lastconnecttime;) is also added to the connection ;). When a new connection is established (after the accept () of listener), the connection instance and thread instance are saved in the hash table; the last connection time is modified during connection receive. In this way, we can know where the connection is and whether the session is active.
You can manage these sessions in the winform program and set the timeout value.

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.