Home > Net >  Socket asynchronous multi-threaded implementation service side, now can only receive the client send
Socket asynchronous multi-threaded implementation service side, now can only receive the client send

Time:11-25

Find a demo on the Internet, a lot of BBS to give an example of a socket asynchronous, I found problem: debug server receives the task can only receive the first a pack of client data, the client then sends the data service client is not received, the debugging, the service side received the first package of data is sent and then execute action, and then jump out of the debugging process,,, the trouble which great god help take a look at why the sample is as follows:
Public static void StartListening ()
{
//Data buffer for the incoming Data.
Byte [] bytes=new byte [1024].

//Establish the local endpoint for a socket.
//The DNS name of The computer
//running the listener is "host.contoso.com".
IPHostEntry ipHostInfo=Dns. GetHostEntry (Dns) GetHostName ());
IPAddress IPAddress=ipHostInfo. Expressions such as AddressList [0];
IPEndPoint localEndPoint=new IPEndPoint (ipAddress, 11000);

//Create a TCP/IP socket.
Socket listener=new Socket (AddressFamily. InterNetwork, SocketType Stream, ProtocolType. Tcp);

//to Bind the socket to the local endpoint and listen for incoming connections.
Try
{
The listener. The Bind (localEndPoint);
Listener. Listen (100);

While (true)
{
//Set the event to nonsignaled state.
AllDone. Reset ();

//Start an asynchronous socket to listen for connections.
Console. WriteLine (" Waiting for a connection... ");
Listener. BeginAccept (new AsyncCallback (AcceptCallback), the listener);

//Wait until a connection is made before continuing.
AllDone. WaitOne ();
}
}
The catch (Exception e)
{
Console. WriteLine (e. oString ());
}
Console. WriteLine (" \ nPress ENTER to continue... ");
The Console. The Read ();
}

Public static void AcceptCallback IAsyncResult (ar)
{
//Signal the main thread to continue.
AllDone. Set ();

//Get the socket that handles the client request.
The Socket listener=(Socket) ar. AsyncState;
The Socket handler=listener. EndAccept (ar);

//Create the state object.
StateObject state=new StateObject ();
State. WorkSocket=handler;
Handler. BeginReceive (state. The buffer, 0, StateObject. BufferSize, 0, new AsyncCallback (ReadCallback), the state);
}

Public static void ReadCallback IAsyncResult (ar)
{
The String content=String. The Empty;

//Retrieve the state object and the handler socket from the asynchronous state object. The
StateObject state=(StateObject) ar. AsyncState;
The Socket handler=state. WorkSocket;

//Read the data from the client socket.
Int bytesRead=handler. EndReceive (ar);

If (bytesRead & gt; 0)
{
//There took be more data, so store the data received so far.
State. Sb. Append (Encoding. The ASCII. Get string (state. The buffer, 0, bytesRead));

//Check for end - of - the file tag. If it is not there, read more data.
The content=state. Sb. ToString ();
If (content. IndexOf (" & lt; EOF>" ) & gt; 1)
{
//All the data from the then read from the client. The Display it on the console.
Console. WriteLine (Read "{0} bytes from the socket. \ n Data: {1}", content. Length, content);
//Echo the data back to the client.
Send (handler, content);
}
The else
{
//Not all data received. Get more.
Handler. BeginReceive (state. The buffer, 0, StateObject. BufferSize, 0, new AsyncCallback (ReadCallback), the state);
}
}
}

Private static void the Send (Socket handler, String data)
{
//Convert the string data to byte data using ASCII encoding.
Byte [] byteData=https://bbs.csdn.net/topics/Encoding.ASCII.GetBytes (data);

//the Begin sending the data to the remote device.
Handler. BeginSend (byteData, 0, byteData. Length, 0, new AsyncCallback (SendCallback), the handler).
}

Private static void SendCallback IAsyncResult (ar)
{
Try
{
//Retrieve the socket from the state object. The
The Socket handler=(Socket) ar. AsyncState;

//Complete sending the data to the remote device.
Int bytesSent=handler. EndSend (ar);
Console. WriteLine (" Sent {0} bytes to the client. ", bytesSent);

Handler. Shutdown (SocketShutdown. Both);
Handler. The Close ();

}
The catch (Exception e)
{
Console. WriteLine (e. oString ());
}
}

CodePudding user response:

In fact the asynchronous be
While (true) variants of the

A - B - A, his cycle, so check your code, look to whether compound this cycle adjustable

We still that sentence, of course, if you are a real project, here is not recommended, in you haven't made the next step, switch to dotnetty immediately, to study the IAsyncResult play inside understand (the situation now is, of course, is this all just said when interest, because now is async/await, rather than the IAsyncResult)

CodePudding user response:

The Socket listener=(Socket) ar. AsyncState;
The Socket handler=listener. EndAccept (ar);

Handler. Shutdown (SocketShutdown. Both);
Handler. The Close ();
You forgot to turn off the listener, add

Listener. Shutdown (SocketShutdown. Both);
The listener. The Close ();
The listener, the handler on the StateObject pass, in addition, the service side you reuse is not going to port?

CodePudding user response:

Research study is good ~ ~ the wheels do not build, wheels and see clear later have what problem can debug,

Why only the server receives a frame, to look at how do you write the client and the server only listening socket connection, even after receiving only once on the data and the so a frame,
Every time your client data, even a server, to a steady stream of data,,,,

nullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnull
  •  Tags:  
  • C#
  • Related