Socket asynchronous communication learning 3. socket Asynchronous Communication

Source: Internet
Author: User

Socket asynchronous communication learning 3. socket Asynchronous Communication

Next, the client uses the synchronous receiving mode. In the SocketClient project, a new SynServer class is created to store the socket server code. Similar to AsynServer, there are four main methods:

There is a global socket, which is used in the following four methods.

Socket socket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );

The class framework is as follows:

 

1. constructor public SynClient (IPEndPoint serverIp)

Input an endpoint parameter to connect to the server. The Code is as follows:

Public SynClient (IPEndPoint serverIp) {Console. writeLine ("** connect to the server **"); socket. connect (serverIp); Console. writeLine ("** connection successful **"); SynSend ("Client: Hello! Server. "); SyncReceive ();}View Code

When the server enables the listening service (Accept (), the client connects to the server through the connect () method. serverIp is the server endpoint address, and the local debugging configuration is 127.0.0.1: port, configure in the main () function.

2. synchronous sending function public int SynSend (string msg)

Public int SynSend (string msg) {Socket socket = this. socket; byte [] data = Encoding. UTF8.GetBytes (msg); try {int sendLength = socket. send (data); Console. writeLine ("SynSend {0} bytes to server: {1} successfully", sendLength, socket. remoteEndPoint. toString ();} catch (SocketException e) {Console. writeLine ("failed to send: {0} \ n Error code: {1}", e. message, e. errorCode); return e. errorCode;} return 0 ;}View Code

3. synchronous receiving function public virtual void SyncReceive ()

Public virtual void SyncReceive () {// StringBuilder sb = new StringBuilder (1024*1024); Thread th = new Thread () => {while (receiveFlag) {byte [] buffer = new byte [1024]; int r = socket. receive (buffer); string receiveStr = Encoding. ASCII. getString (buffer, 0, r); Console. writeLine (receiveStr); // sb. appendFormat ("{0}", Encoding. ASCII. getString (buffer, 0, r) ;}}); th. start ();}View Code

Different from asynchronous transmission and receiving, the system does not automatically open a thread like asynchronous transmission and receiving, so SynSend () hinders the main thread because it is only sent once, therefore, the thread is not manually opened for it, and SyncReceive () opens a thread for it. The while loop is used in the thread to keep receiving, and other services can be processed by the program during the receiving process.

4. Release the resource function public void Close ()

Public void Close () {socket. Dispose (); socket. Close ();}View Code

After both the server and client classes are written, let's debug and configure the endpoint in the two main functions and call the service class, as shown below:

Server: Use the local address 127.0.0.1, port 8888

Client: the endpoint address is the same as the listening address opened on the server.

In addition, the framework in the first article contains a typo, Which is intercepted once ------

The final result of the subsequent test is as follows:

The communication succeeds. The client receives the message from the server and the server also receives the message from the client.

In the first three articles, the most basic communication is completed. Next, we will add communication control and solve the packet Sticking Problem During reception. If you think there are any shortcomings in this blog post, you can point out that I am trying to improve my skills and skills :-)

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.