C #-based socket entry

Source: Internet
Author: User
Tags getstream

First, explain the network communication using the socket interface in principle. Here we use the most common C/S mode as an example. First, the server has a process (or multiple processes) wait for the customer to connect to the specified port, and the service program waits for the customer's connection information. Once connected, the data can be transmitted according to the designed data exchange method and format. The client sends a connection request to the server whenever necessary. For ease of understanding, some calls and their general functions are mentioned here. After a socket call is used, only one socket descriptor can be used. At this time, communication is not allowed, and other calls are required, to complete the information used in the structure indicated by the socket.

When the TCP protocol is used, the server-side process first uses the SOCKET call to obtain a descriptor, and then uses the bind Call to connect a name to the socket descriptor, for an internet domain, the Internet address is associated with a socket. Then, the server uses the listen call to specify the length of the queue waiting for service requests. Then you can use accept to call and wait for the client to initiate a connection. Generally, it is to block and wait for the connection. Once a client sends a connection, accept returns the client's address information and a new socket descriptor, this descriptor has the same features as the original socket, and the server can use this new socket for read/write operations. Generally, the server may create a new process after the Accept return to communicate with the customer, and the parent process then waits for another connection at the Accept call. Client processes generally use socket to obtain a socket descriptor, and then use connect to initiate a connection to the specified port on the specified server. Once the connection is successful, it indicates that a connection has been established with the server. Then, you can perform read and write operations through the socket descriptor.

. Netframework provides the system. net. Socket namespace for socket communication. The namespace contains the following important classes:

· Socket classThis lower-level class is used internally to manage connections, webrequest, tcpclient, and udpclient.

· Networkstream classThis class is derived from stream, which indicates data streams from the network.

· Tcpclient classAllow the creation and use of TCP connections

· Tcplistener classAllow listening for incoming TCP connection requests

· Udpclient classUsed to create connections for UDP clients (UDP is another TCP protocol, but it is not widely used and is mainly used in local networks)

Next we will look at a socket-based dual-machine communication code C # version

First, create an instance of the socket object, which can be achieved through the socket class constructor:

PublicSocket (addressfamilyAddressfamily, sockettypeSockettype, protocoltypeProtocoltype );

AddressfamilyParameter specifiedSocketThe addressing scheme used, sockettypeParameter specifiedSocketType, protocoltypeParameter specifiedSocketThe protocol used.

The following example createsSocket, which can be used inTCP/IPNetwork (suchCommunication on the Internet.

SocketTemp=NewSocket (addressfamily. InterNetwork,Sockettype. stream,Protocoltype. TCP );

To useUDPInsteadTCP, you need to change the protocol type, as shown in the following example:

SocketTemp=NewSocket (addressfamily. InterNetwork,Sockettype. dgram,Protocoltype. UDP );

Once createdSocket, on the client side, you can connect to the specified server through the connect method (you can bind the port before the connect method, that is, initiate a connection with the specified port, if you do not bind the port number beforehand, by default, the system binds a random port number between 1024 and 5000), sends data to the remote server through the send method, and then receives data from the server through the receive method, you need to bind the specified interface using the bind method to associate the socket with a local endpoint and listen for requests on the interface using the listen method. When listening for connections to the user end, call accept to complete the connection operation. Create a new socket to process incoming connection requests. End of useSocketAnd then useCloseMethod disabledSocket.

It can be seen that many of the above methods contain endpoint parameters, in the Internet, TCP/IPA network address and a service port number are used to uniquely identify a device. The network address identifies a specific device on the network, and the port number identifies a specific service on the device to be connected. The combination of network addresses and service ports is called an endpoint.. NetIn the FrameworkEndpointClass indicates the endpoint. It provides the abstraction of network resources or services to indicate network addresses and other information .. Net is also defined for each supported address familyEndpointForIPAddress family, which isIpendpoint. IpendpointClass contains the host and port information required by the application to connect to the service on the host, through the Host IP address and port number of the combined service, ipendpointClass to form the connection point of the service.

When using the ipendpoint class, the computer ip address is inevitably involved. There are two types of IP address instances available in the system. Net namespace:

· IPaddress class: IPaddressClass includes computers inIPThe address on the network. The parse method can setIPAddress stringIPaddressInstance. The following statement createsIPaddressInstance:

IPaddressMyip=IPaddress. parse ("192.168.0.1 ");

You need to know: SocketClass supports two basic modes: synchronous and asynchronous. The difference is that in synchronization mode, the network operation functions (suchSendAndReceive) until all content transfer operations are completed, the control is returned to the caller. In asynchronous mode, the message is transmitted by bit. You must specify the start and end of the message. The synchronization mode is the most commonly used mode, and the example here also uses the synchronization mode.

The following is a complete example. The client sends a test string to the server. The server receives and displays the string and returns a successful response to the client.

// Client
UsingSystem;
UsingSystem. text;
UsingSystem. IO;
UsingSystem. net;
UsingSystem. net. Sockets;
NamespaceSocketsample
{
ClassClass1
{
StaticVoidMain ()
{
Try
{
IntPort=2000;
StringHost="127.0.0.1 ";
IPaddressIP=IPaddress. parse (host );
IpendpointIPE=NewIpendpoint (IP,Port); // convert the IP address and port to an ipendpoint instance
SocketC=NewSocket (addressfamily. InterNetwork,Sockettype. stream,Protocoltype. TCP); // create a socket
Console. writeline ("conneting ...");
C. Connect (IPE); // connect to the server
StringSendstr="Hello! ThisIsASocketTest ";
Byte []BS=Encoding. ASCII. getbytes (sendstr );
Console. writeline ("SendMessage ");
C. Send (BS,BS. length,0); // send test information
StringRecvstr="";
Byte []Recvbytes=NewByte [2, 1024];
IntBytes;
Bytes=C. Receive (recvbytes,Recvbytes. length,0); // The slave server accepts the returned information
Recvstr+ =Encoding. ASCII. getstring (recvbytes,0,Bytes );
Console. writeline ("clientGetMessage: {0 }",Recvstr); // display the Server Response Information
C. Close ();
}
Catch(ArgumentnullexceptionE)
{
Console. writeline ("argumentnullexception:{0 }",E );
}
Catch(SocketexceptionE)
{
Console. writeline ("socketexception:{0 }",E );
}
Console. writeline ("PressEnterToExit ");
Console. Readline ();
}
}
}
// Server end
UsingSystem;
UsingSystem. text;
UsingSystem. IO;
UsingSystem. net;
UsingSystem. net. Sockets;
NamespaceProject1
{
ClassClass2
{
StaticVoidMain ()
{
Try
{
IntPort=2000;
StringHost="127.0.0.1 ";
IPaddressIP=IPaddress. parse (host );
IpendpointIPE=NewIpendpoint (IP,Port );
SocketS=NewSocket (addressfamily. InterNetwork,Sockettype. stream,Protocoltype. TCP); // create a socket class
S. BIND (IPE); // bind port 2000
S. Listen (0); // start listening
Console. writeline ("WaitForConnect ");
SocketTemp=S. Accept (); // create a new socket for the new connection.
Console. writeline ("GetAConnect ");
StringRecvstr="";
Byte []Recvbytes=NewByte [2, 1024];
IntBytes;
Bytes=Temp. Receive (recvbytes,Recvbytes. length,0); // receive information from the client
Recvstr+ =Encoding. ASCII. getstring (recvbytes,0,Bytes );
Console. writeline ("ServerGetMessage: {0} ", recvstr); // display the information sent from the client.
StringSendstr="OK! ClientSendMessageSucessful! ";
Byte []BS=Encoding. ASCII. getbytes (sendstr );
Temp. Send (BS,BS. length,0); // return the client success message
Temp. Close ();
S. Close ();
}
Catch(ArgumentnullexceptionE)
{
Console. writeline ("argumentnullexception:{0 }",E );
}
Catch(SocketexceptionE)
{
Console. writeline ("socketexception:{0 }",E );
}
Console. writeline ("PressEnterToExit ");
Console. Readline ();
}
}
}

The preceding example uses the socket class. The system. net. Socket namespace also provides two abstract advanced classes: tcpclient, udpclient, and networkstream for communication stream processing. Let's take a look at the example below.

Client

TcpclientTcpclient = newTcpclient (Host IP address and port number );
NetworkstreamNS = tcp. client. getstream ();

Server

TcplistenerTcplistener = newTcplistener (listener port );
Tcplistener. Start ();
TcpclientTcpclient = tcplistener. accepttcpclient ();
NetworkstreamNS = tcpclient. getstream ();

The server uses tcplistener to listen, instantiate the connected object as a tcpclient, and call tcpclient. the getstream () method returns the network stream instantiated as a networlstream stream. The following describes how to send and receive streams.

If udpclient is used, udpclient is directly instantiated and then the send and receive methods of udpclient are called. Note that udpclient does not return network streams, that is, there is no getstream method, therefore, it cannot be streamed. When UDP is used for communication, do not listen to the server.

Now we know about. net.The socket communication process is as follows: a slightly complex program and a broadcast C/S chat program.

The client design requires a ListBox to display the chat content. A textbox inputs what you want to say, a button sends a message, and a button establishes a connection.

Click the button to create a connection. A dialog box is displayed, prompting you to enter the IP address, port, and nickname of the connection server to start an acceptance thread, receives information from the server and displays it on ListBox.

The server has two buttons, one starting service, one t dropping the client with established connection, and one ListBox displaying the IP address and port of the Client Connected to the server.

The most important thing is the issue of string encoding. You need to encode the string to be transmitted according to utf8, and then restore it to gb2312 when accepting the code. Otherwise, the Chinese display will be garbled.

Another is the receiving thread. Here I write a while (ture) loop to constantly judge whether there is information flowing in. If there is any, it will receive it and display it on ListBox. There is a problem here. in net2.0, an exception is thrown when the staggered thread modifies the properties of the form space. It cannot be modified directly. You need to define a delegate to modify it.

When the client needs to be disconnected, such as clicking XX in the upper-right corner of the form, you need to define this. formclosing+ =NewSystem. windows. forms. formclosingeventhandler (this. closing );(. net2.0 is a formclosing System Event). In the closing () function, the server sends the close character to the server. The server judges the information sent from the client on all connections cyclically. If it starts with close, disconnect from the instance. If I enter close in the chat window, will the connection be disconnected? No, the IP address and nickname must be added at the beginning when the information entered in the chat window is sent to the server, so there is no 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.