A case study of c#2.0 socket socket Programming 200

Source: Internet
Author: User
Tags getstream

First of all, explain the principle of using the Socket Interface network communication, where the most commonly used C/s mode as an example, first, the server has a process (or multiple processes) on the specified port waiting for the client to connect, the service program waits for the customer's connection information, once connected, Data transfer can be carried out according to the design method and format. The client issues a connection request to the server at the required time. For the sake of understanding, some calls and their approximate functions are mentioned here. With the socket call, only one socket descriptor can be used, and no communication is possible, and other calls are used to make the information used in the structure referred to by the socket filled out.

When using the TCP protocol, the generic service-side process uses the socket call to get a descriptor, and then uses the bind call to connect a name to the socket descriptor, which is the Internet domain to associate the Internet address to the socket. After that, the server uses the listen call to indicate the length of the queue waiting for the service request. You can then use the accept call to wait for the client to initiate a connection, typically blocking the wait connection, once a client makes 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 generic server may create a new process to communicate with the client after the accept returns, and the parent process waits for another connection at the accept call. The client process typically uses the socket call to get a socket descriptor and 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 can be used to read and write.

. NETFramework provides a System.Net.Socket namespace for socket communication, which has the following common and important classes in this namespace:

· The socket class is a low-level class for managing connections, and Webrequest,tcpclient and UdpClient use this class internally.

· The NetworkStream class is derived from stream, which represents a stream of data from the network

· The TcpClient class allows you to create and use TCP connections

· The TcpListener class allows incoming TCP connection requests to be monitored

· The UdpClient class is used for UDP client-created connections (UDP is another TCP protocol but not widely used, mainly for local networks)

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

First, you create an instance of the socket object, which can be implemented 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 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 the Socket is created, on the client side, you will be able to connect to the specified server via the Connect method (you can either bind the port before the Connect method, or initiate the connection with the specified port, if you do not have the bind port number in advance), The system will randomly bind a port number from 1024 to 5000 by default, and send data to the remote server via the Send method, which can then receive data from the server via receive; You need to bind the socket to a local endpoint using the Bind method binding, and listen for requests on that interface through the Listen method, and when listening to the client's connection, call accept to complete the connection and create a new socket to handle the incoming connection request. When you are finished using the socket, close the socket using the Close method.

As you can see, many of these methods contain parameters for the endpoint type, and in the Internet, 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 network address and service port is called an endpoint, which is represented by the EndPoint class in the. NET framework, which provides an abstraction that represents a network resource or service that flags information such as a network address. NET also defines the descendants of the 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 the connection point to the service by combining the host IP address and port number of the service.

When using the IPEndPoint class, it is unavoidable to refer to the IP address of the computer, there are two kinds of IP address instances in the System.Net namespace:

· 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 transfer, the call to a function that performs network operations (such as Send and Receive) waits until all the content delivery operations have completed before returning control to the calling program. In asynchronous mode, a bitwise transfer is required to specify the start and end of the send. Synchronous mode is the most commonly used mode, and our example here is also using the synchronous mode.

Here is a complete example where the client sends a test string to the server, which the server receives and displays, giving 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 port 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 Port 2000
S.listen (0);//Start monitoring
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 the client
Recvstr + = Encoding.ASCII.GetString (recvbytes, 0, bytes);
Console.WriteLine ("Server Get message:{0}", recvstr);//Display the 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 using the socket class, the System.Net.Socket namespace also provides two abstract advanced classes TcpClient and UdpClient and NetworkStream for communication flow processing, let's take a 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 server is monitored with TcpListener, then the connected object is instantiated into a tcpclient, the Tcpclient.getstream () method is called, the return network stream is instantiated as a networlstream stream, and the following is the method of the stream to send, Receive

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

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

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

Click on the Connect button and a dialog box prompts you to enter the IP, port, and nickname of the connection server, start an accept thread, accept the message from the server and display it on the listbox.

Server-Side 2 button, one boot service, one t off the 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 encoding, the need to transfer the string according to UTF8 code, and then accept the time to revert to GB2312, otherwise the Chinese display will be garbled.

There is also a receive thread, here I simply write a while (ture) loop, constantly judge whether there is information flow, there is on the receive, and displayed in the ListBox, here is the problem, in. Net2.0 inside, when the interleaving thread modifies the form space property, it throws an exception, cannot be modified directly, and needs to define a delegate to modify.

When the client needs to disconnect, such as clicking on the XX in the upper-right corner of the form, you need to define this. FormClosing + = new System.Windows.Forms.FormClosingEventHandler (this. Closing); (. Net2.0 is a formclosing system event), in the Closing () function, send the close character to the server, the servers determine the loop to determine all the connections on the client from the message, if you start with close, disconnect its connection. See here, the reader will ask, if I am in the Chat window to enter close is not also disconnected? No, in the Chat window input information to the server when the beginning to add IP information and nickname, so there is no conflict.

A case study of c#2.0 socket socket Programming 200

Related Article

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.