Socket Basic Concepts:
Sockets are the cornerstone of communication, and are the basic operating unit of network communication that supports TCP/IP protocol. Sockets can be viewed as endpoints of two-way communication between different host processes, which form the programming interface between a single host and the entire network. Sockets exist in the communication domain, which is an abstract concept that is introduced in order to handle a generic thread through socket communication. Sockets typically exchange data with sockets in the same domain (data interchange may also traverse the bounds of the domain, but some interpreter must be executed at this point). Various processes use this same domain to communicate with each other using an Internet Protocol cluster.
Sockets can be categorized according to the nature of the communication, which is visible to the user. Applications typically communicate only between sockets of the same class. However, as long as the underlying communication protocol allows, the different types of sockets can still be communicated. There are two different types of sockets: Stream sockets and datagram sockets.
How sockets work:
To communicate over the Internet, you need at least a pair of sockets, one running on the client side, what we call Clientsocket and the other running on the server side, which we call ServerSocket.
The connection between sockets can be divided into three steps, depending on how the connection is started and the destination to which the local socket is connected: server listening, client requests, connection confirmation.
The so-called server monitoring, is the server-side sockets do not locate specific client sockets, but in the state of waiting for connection, real-time monitoring network status.
The so-called client request, refers to the client socket to make a connection request, to connect the target is the server-side sockets. To do this, the socket for the client must first describe the socket of the server to which it is connecting, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.
Connection confirmation means that when a server-side socket is heard or received a connection request from a client socket, it responds to the client socket request, creates a new thread, sends the server-side socket description to the client, and once the client confirms the description, the connection is established. While the server-side socket continues to be listening, it continues to receive connection requests from other client sockets.
socket Programming instances in C #:
By simply introducing the basic concepts of sockets and the basic principles of socket programming, I think we have a preliminary understanding of socket programming. However, the above mentioned is only the basic concepts and principles, to really use or need a certain work. The best way to really understand the basic concepts and principles is to do a hands-on example, I will introduce a good example of using C # to implement socket programming-chat room program.
This program is based on C/S (Server/client) architecture, the program contains a server-side application and a client application. First, run the server-side application on the server, and the program starts the server monitor as soon as it runs. The client's application can then be opened on the client computer. When the program is opened, it can connect to the server-side application, that is, the client request. After the connection is confirmed, the client user can chat with other client users. There is no limit on the number of clients, while also supporting the "private conversation" chat mode, support chat record. So this is a pretty good example of learning socket programming. Furthermore, multithreaded mechanisms are used in the program to process information for each client. After each client and server-side connection succeeds, a thread is established between them. After using multithreading, the client does not interact with each other, even if one of the errors does not affect the other.
Let me give you a specific example of this:
Server-side programs:
1. Open Vs.net and create a new C # template for Windows applications, which you might name as "Chatserver."
2. Layout interface. Simply add a ListBox control to the interface, which is used primarily to display some information about the client's users. The image is as follows:
3. The code for the server-side program is written.
For the server side, the primary role is to listen for the client's connection request and confirm its request. The program opens a startlistening () thread at the beginning.
private void Startlistening ()
{
Listener = new TcpListener (listenport);
Listener. Start ();
while (true)
{
Try
{
Socket s = listener. AcceptSocket ();
Clientsocket = s;
ClientService = new Thread (new ThreadStart (serviceclient));
ClientService. Start ();
}
catch (Exception e)
{
Console.WriteLine (E.tostring ());
}
}
}
The thread is always in a running state. When the server side receives a connection request from the client, it opens a serviceclient () thread service client. When a connection is established, each client is given a socket that belongs to it. At the same time, objects of a client class are created. This object contains some relevant information about the client, which is saved in an array list. The client class is as follows (see also Client.cs files in source code):
Using System;
Using System.Threading;
Namespace Chatserver
{
Using System.Net.Sockets;
Using System.Net;
///
A summary description of the Client.
///
public class Client
{
Private Thread Clthread;
Private EndPoint EndPoint;
private string name;
Private Socket sock;
Public Client (String _name, EndPoint _endpoint, Thread _thread, Socket _sock)
{
TODO: Add constructor logic here
Clthread = _thread;
Endpoint = _endpoint;
name = _name;
sock = _sock;
}
public override string ToString ()
{
Return endpoint. ToString () + ":" + name;
}
Public Thread Clthread
{
Get{return Clthread;}
Set{clthread = value;}
}
Public EndPoint Host
{
Get{return endpoint;}
Set{endpoint = value;}
}
public string Name
{
Get{return name;}
Set{name = value;}
}
Public Socket Sock
{
Get{return Sock;}
Set{sock = value;}
}
}
}
The body part of the program should be the ServiceClient () function. The function is a separate thread whose main part is a while loop. In the loop body, the program handles various client commands. The server side receives an ASCII-code string from the client that contains a "|" The delimiter in the form. "|" in the string The previous sections are specific commands, including Conn, CHAT, PRIV, gone four types. The conn command creates a new client connection, sends an existing list of users to a new user and informs other users that a new user is joining. The chat command sends new information to all users. The Priv command sends a WHISPER message to a user. The Gone command removes a left user from the list of users and informs other users that So-and-so has left. At the same time, the Gone command can set the Boolean variable keepalive to False to end the thread that connects to the client. The ServiceClient () function is as follows:
private void ServiceClient ()
{
Socket client = Clientsocket;
BOOL KeepAlive = true;
while (keepalive)
{
byte[] buffer = new byte[1024];
Client. Receive (buffer);
String clientcommand = System.Text.Encoding.ASCII.GetString (buffer);
string[] tokens = Clientcommand. Split (New char[]{' | '});
Console.WriteLine (Clientcommand);
if (tokens[0] = = "CONN")
{
for (int n=0; n< n++) >
{
Client CL = (client) clients[n];
Sendtoclient (cl, "join|" + tokens[1]);
}
EndPoint EP = client. Remoteendpoint;
Client C = new Client (Tokens[1], EP, ClientService, Client);
Clients. ADD (c);
String message = "list|" + getchatterlist () + "/r/n";
Sendtoclient (c, message);
LBCLIENTS.ITEMS.ADD (c);
}
if (tokens[0] = = "CHAT")
{
for (int n=0; n< n++) >
{
Client CL = (client) clients[n];
Sendtoclient (cl, clientcommand);
}
}
if (tokens[0] = = "PRIV")
{
String destclient = Tokens[3];
for (int n=0; n< n++) >
{
Client CL = (client) clients[n];
if (Cl.Name.CompareTo (tokens[3]) = = 0)
Sendtoclient (cl, clientcommand);
if (Cl.Name.CompareTo (tokens[1]) = = 0)
Sendtoclient (cl, clientcommand);
}
}
if (tokens[0] = = "GONE")
{
int remove = 0;
BOOL found = false;
int c = clients. Count;
for (int n=0; n< n++) >
{
Client CL = (client) clients[n];
Sendtoclient (cl, clientcommand);
if (Cl.Name.CompareTo (tokens[1]) = = 0)
{
remove = N;
Found = true;
LbClients.Items.Remove (CL);
}
}
if (found)
Clients. RemoveAt (remove);
Client. Close ();
KeepAlive = false;
}
}
}
In this way, the server-side program is basically complete. (Other slightly minor code can see the Form1.cs file in source code) the program runs as shown below: