Use. NET access to the Internet (4) Paul

Source: Internet
Author: User
Tags connect socket tostring
This section of the Acceptcallback method that starts receiving data from a client socket first initializes an instance of the StateObject class, and then calls the BeginReceive method to begin the asynchronous reading of the data from the client socket.

The following example shows the complete Acceptcallback method. It assumes that there is a ManualResetEvent instance named Alldone, defines the StateObject class, and defines the Readcallback method in a class named SocketListener.

[C #]
public static void Acceptcallback (IAsyncResult ar) {
Get the socket that handles the client request.
Socket listener = (socket) ar. asyncstate;
Socket handler = listener. Endaccept (AR);

Signal the main thread to continue.
Alldone.set ();

Create the state object.
StateObject state = new StateObject ();
State.worksocket = handler;
Handler. BeginReceive (state.buffer, 0, stateobject.buffersize, 0,
New AsyncCallback (Asynchronoussocketlistener.readcallback), state);
}
The final method that needs to be implemented for an asynchronous socket server is a read callback method that returns the data sent by the client. As with the accept callback method, the read callback method is also a AsyncCallback delegate. This method reads one or more bytes from the client socket into the data buffer, and then calls the BeginReceive method again until the data sent by the client is complete. After reading the entire message from the client, the string is displayed on the console and the server socket that handles the connection to the client is turned off.

The following example implements the Readcallback method. It assumes that the StateObject class is defined.

[C #]
public void Readcallback (IAsyncResult ar) {
StateObject state = (stateobject) ar. asyncstate;
Socket handler = state. Worksocket;

Read data from the client socket.
int read = handler. EndReceive (AR);

Data is read from the client socket.
if (Read > 0) {
State.sb.Append (Encoding.ASCII.GetString (State.buffer,0,read));
Handler. BeginReceive (state.buffer,0,stateobject.buffersize, 0,
New AsyncCallback (Readcallback), state);
} else {
if (State.sb.Length > 1) {
All of the data has been read from the client;
Display it on the console.
String content = State.sb.ToString ();
Console.WriteLine ("Read {0} bytes from socket.\n Data: {1}",
Content. Length, content);
}
Handler. Close ();
}
}
Synchronizing client Sockets sample
The following example program creates a client that is connected to the server. The client is generated with a synchronous socket, so the execution of the client application is suspended until the server returns a response. The application sends a string to the server and then displays the string returned by the server in the console.

[C #]
Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;

public class Synchronoussocketclient {

public static void Startclient () {
Data buffer for incoming data.
byte[] bytes = new byte[1024];

Connect to a remote device.
try {
Establish the remote endpoint for the socket.
The name of the
Remote device is "host.contoso.com".
Iphostentry iphostinfo = dns.resolve ("host.contoso.com");
IPAddress ipaddress = iphostinfo.addresslist[0];
IPEndPoint remoteep = new IPEndPoint (ipaddress,11000);

Create a TCP/IP socket.
Socket sender = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, PROTOCOLTYPE.TCP);

Connect the socket to the remote endpoint. Catch any errors.
try {
Sender. Connect (remoteEP);

Console.WriteLine ("Socket connected to {0}",
Sender. Remoteendpoint.tostring ());

Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes ("This is a test<eof>");

Send the data through the socket.
int bytessent = sender. Send (msg);

Receive the response from the remote device.
int Bytesrec = sender. Receive (bytes);
Console.WriteLine ("echoed Test = {0}",
Encoding.ASCII.GetString (Bytes,0,bytesrec));

Release the socket.
Sender. Shutdown (Socketshutdown.both);
Sender. Close ();

catch (ArgumentNullException ane) {
Console.WriteLine ("ArgumentNullException: {0}", ane.) ToString ());
catch (SocketException se) {
Console.WriteLine ("SocketException: {0}", se.) ToString ());
catch (Exception e) {
Console.WriteLine ("Unexpected exception: {0}", e.tostring ());
}

catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}

public static int Main (string[] args) {
Startclient ();
return 0;
}
}


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.