A study on C # 2.0 socket Programming Example

Source: Internet
Author: User
Tags bind exit functions getstream connect socket thread port number
Programming first from the principle of the use of Socket Interface network communication, here with the most commonly used C/s mode as an example, first, the server has a process (or multiple processes) in the specified port waiting for customers to connect, service program waiting for customer connection information, once connected, Data can be transmitted according to the method and format of the design. The client issues a connection request to the server at the required time. Here, for the sake of understanding, some calls and their approximate functions are mentioned. After using the socket call, only one socket descriptor can be used, which cannot be communicated, and other calls are made so that the information used in the structure referred to by the socket is filled out.

When using the TCP protocol, the General Service-side process first uses the socket call to get a descriptor and then joins a name with the socket descriptor using the bind call, which is to connect the Internet address to the socket for the Internet domain. The service side then uses the listen call to indicate the length of the Wait service request queue. You can then use the accept call to wait for the client to initiate a connection, typically blocking the wait connection, and once a client issues a connection, accept returns the customer's address information and returns a new socket descriptor that has the same characteristics as the original socket. The server can then use this new socket for read and write operations. The General Service side may create a new process to communicate with the customer after accept returns, and the parent process waits for another connection at the accept call. The client process typically uses a socket call to get a socket descriptor, then uses connect to initiate a connection to the specified port on the specified server, and once the connection is successfully returned, the connection to the server is established, and the socket descriptor is used to read and write.

. NETFramework provides a System.Net.Socket namespace for socket communication, in which there are several important classes that are commonly used:

· Socket class This low-level class is used to manage connections, and webrequest,tcpclient and UdpClient use this class internally.

· NetworkStream class This class is derived from the stream, which represents the flow of data from the network

· TcpClient class allows TCP connections to be created and used

· TcpListener class allows incoming TCP connection requests to be monitored

· UdpClient class for UDP client creation connections (UDP is another TCP protocol, but not widely used, primarily for local networks)

Let's look at a C # version of the two-machine communication code based on the socket

You first create an instance of the socket object, which can be done by constructing the socket class:

Public Socket (addressfamily addressfamily,sockettype sockettype,protocoltype protocoltype);
Where the AddressFamily parameter specifies the addressing scheme used by the socket, the SocketType parameter specifies the type of the socket, and the ProtocolType parameter specifies the protocol used by the socket.

The following example statement creates a Socket that can be used to communicate on a TCP/ip-based network, such as the Internet.

Socket TEMP = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
To use UDP instead of TCP, you need to change the protocol type, as shown in the following example:

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


Once you create the Socket, on the client side, you will be able to connect to the specified server via the Connect method (you can initiate the connection at the Connect method before the bind port, or on the specified port, if you do not bind the port number beforehand. The system defaults to 1024 to 5000 randomly binding a port number and sends data to the remote server via the Send method, which can then receive data from the server via receive; You need to bind the specified interface with the Bind method to make the socket connected to a local endpoint and listen for requests on that interface through the Listen method, calling accept to complete the connection, and creating a new socket to handle incoming connection requests, when the connection is heard from the client. When you are finished using the socket, close the socket with the closing method.

As you can see, many of these methods contain parameters for the endpoint type, in which TCP/IP uses a network address and a service port number to uniquely identify the device. The network address identifies a specific device on the network, and the port number identifies the specific service on the device to which you want to connect. The combination of a network address and a service port is called an endpoint, and it is the EndPoint class that represents the endpoint in the. NET framework, providing an abstraction that represents a network resource or service, to mark information such as a network address. NET also defines the descendants of EndPoint for each supported address family, and for the IP address family, the class is IPEndPoint. The IPEndPoint class contains the host and port information required by the application to connect to the service on the host, and the IPEndPoint class forms to the service's connection point by combining the host IP address and port number of the service.

When the IPEndPoint class is used, it inevitably involves the IP address of the computer, and there are two kinds of system.net namespaces that can get an IP address instance:

· IPAddress class: The IPAddress class contains the address of the computer on the IP network. Its Parse method converts an IP address string to an IPAddress instance. The following statement creates a IPAddress instance:

IPAddress MyIP = Ipaddress.parse ("192.168.0.1");
What you need to know is that the Socket class supports two basic modes: synchronous and asynchronous. The difference is that in synchronous mode, a block is transferred, and calls to functions that perform network operations, such as Send and Receive, wait until all content transfer operations have completed before returning control to the caller. In asynchronous mode, a bitwise transfer requires specifying the start and end of the send. Synchronization mode is the most common pattern, and our example here is the use of synchronous mode.

Looking at a complete example, the client sends a test string to the server that the server receives and displays to give the client a successful response.

Client Side
Using System;
Using System.Text;
Using System.IO;
Using System.Net;
Using System.Net.Sockets;
Namespace Socketsample
{
Class Class1
{
static void Main ()
{
Try
{
int port = 2000;
String host = "127.0.0.1";
IPAddress IP = ipaddress.parse (host);
IPEndPoint ipe = new IPEndPoint (IP, port);//Convert IP and ports to IPEndPoint instance
Socket c = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);//Create a socket
Console.WriteLine ("Conneting ...");
C.connect (IPE);//Connect to Server
String sendstr = "hello! This is a socket test ";
byte[] bs = Encoding.ASCII.GetBytes (SENDSTR);
Console.WriteLine ("Send message");
C.send (BS, BS.) Length, 0);//Send test information
String recvstr = "";
byte[] recvbytes = new byte[1024];
int bytes;
bytes = C.receive (recvbytes, recvbytes.length, 0);//Accept return information from server side
Recvstr + + Encoding.ASCII.GetString (recvbytes, 0, bytes);
Console.WriteLine ("Client Get Message:{0}", recvstr);//display server return information
C.close ();
}
catch (ArgumentNullException e)
{
Console.WriteLine ("ArgumentNullException: {0}", e);
}
catch (SocketException E)
{
Console.WriteLine ("SocketException: {0}", e);
}
Console.WriteLine ("Press Enter to Exit");
Console.ReadLine ();
}
}
}
Server Side
Using System;
Using System.Text;
Using System.IO;
Using System.Net;
Using System.Net.Sockets;
Namespace Project1
{
Class Class2
{
static void Main ()
{
Try
{
int port = 2000;
String host = "127.0.0.1";
IPAddress IP = ipaddress.parse (host);
IPEndPoint ipe = new IPEndPoint (IP, port);
Socket s = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);//Create a Socket class
S.bind (IPE);//Bind 2000 port
S.listen (0);/start listening
Console.WriteLine ("Wait for Connect");
Socket temp = s.accept ();//Create a new socket for the new connection.
Console.WriteLine ("Get a Connect");
String recvstr = "";
byte[] recvbytes = new byte[1024];
int bytes;
bytes = Temp. Receive (Recvbytes, recvbytes.length, 0);//Receive information from client
Recvstr + + Encoding.ASCII.GetString (recvbytes, 0, bytes);
Console.WriteLine ("Server Get Message:{0}", recvstr);//display information from the client
String sendstr = "ok! Client Send message sucessful! ";
byte[] bs = Encoding.ASCII.GetBytes (SENDSTR);
Temp. Send (BS, BS.) Length, 0)//Return Client Success Information
Temp. Close ();
S.close ();
}
catch (ArgumentNullException e)
{
Console.WriteLine ("ArgumentNullException: {0}", e);
}
catch (SocketException E)
{
Console.WriteLine ("SocketException: {0}", e);
}
Console.WriteLine ("Press Enter to Exit");
Console.ReadLine ();
}
}
}
The above example is the socket class used, and the System.Net.Socket namespace also provides two abstract high-level classes tcpclient and UdpClient and networkstream for traffic flow processing, let's look at the example

Client

TcpClient tcpclient=new tcpclient (host IP, port number);
NetworkStream ns=tcp. Client.getstream ();
Service side

TcpListener tcplistener=new TcpListener (listening port);
Tcplistener.start ();
TcpClient tcpclient=tcplistener.accepttcpclient ();
NetworkStream Ns=tcpclient.getstream ();
The service end listens with TcpListener, then instantiates the connected object as a TcpClient, invokes the Tcpclient.getstream () method, returns the network stream instance to a Networlstream stream, and the following is the stream method for send. Receive

If it is udpclient, then directly udpclient instantiation, and then call UdpClient send and receive method, need to pay attention to, udpclient not return network flow method, that is, there is no GetStream method, so can not be fluidization , and do not listen to the server when using UDP communication.

Now that we have a general understanding of the flow of. Net socket communication, let's make a slightly more complex program, a broadcast of C/S chat program.

The client design requires a 1 listbox to display the chat content, a textbox to enter what you want to say, a button to send a message, a button to establish the connection.

Click to establish a link button to come out a dialog box, prompted to enter the server's IP, port, and your nickname, start an acceptance thread, responsible for receiving information from the server and displayed on the listbox.

Server-Side 2 button, one boot service, one t off a client that has established a connection, a listbox displays the IP and port of the client on the connection.

The more important place is the problem of string coding, the need to send the required string according to UTF8 code, and then accept the time to revert to become GB2312, otherwise the Chinese display will be garbled.

There is also a receiving thread, I here simply write a while (ture) loop, constantly judge whether there is information inflow, there will be received, and displayed in the ListBox, there are problems, in. Inside the Net2.0, when a interleaved thread modifies a form's space attribute, it throws an exception that cannot be modified directly, and a delegate needs to be defined to modify it.

When the client needs to disconnect, for example, click XX in the upper right corner of the form, you need to define a this. FormClosing + = new System.Windows.Forms.FormClosingEventHandler (this. Closing); (. Net2.0 is a formclosing system event), within the Closing () function, send the close character to the server, and the servers judge the loop to determine the information from the client on all connections, and disconnect it if it starts with close. See here, the reader will ask, if I enter close in the chat window is not also disconnected? No, the information entered in the Chat window to the server at the beginning of the message to add IP information and nickname, so will not conflict.

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.