Use. NET access to the Internet (5) Paul

Source: Internet
Author: User
Tags execution connect socket string back tostring client port number

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.
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;
}
}

Synchronization server Sockets sample


The following example program creates a server that receives connection requests from clients. The server is generated with a synchronous socket, so the execution of the server application is not suspended while waiting for a connection from the client. The application receives a string from the client, displays the string in the console, and then echoes the string back to the client. The string from the client must contain the string "<EOF>" to emit a signal indicating the end of the message.
[C #]
Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
public class Synchronoussocketlistener {
Incoming data from the client.
public static string data = NULL;
public static void Startlistening () {
Data buffer for incoming data.
byte[] bytes = new byte[1024];
Establish the local endpoint for the socket.
Host running the application.
Iphostentry iphostinfo = Dns.resolve (Dns.gethostname ());
IPAddress ipaddress = iphostinfo.addresslist[0];
IPEndPoint localendpoint = new IPEndPoint (ipaddress, 11000);
Create a TCP/IP socket.
Socket listener = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, PROTOCOLTYPE.TCP);
Listen for incoming connections.
try {
Listener. Bind (Localendpoint);
Listener. Listen (10);
Start listening for connections.
while (true) {
Console.WriteLine ("Waiting for a Connection ...");
Program was suspended while waiting for a incoming connection.
Socket handler = listener. Accept ();
data = null;
An incoming connection needs is processed.
while (true) {
bytes = new byte[1024];
int Bytesrec = handler. Receive (bytes);
Data + + Encoding.ASCII.GetString (BYTES,0,BYTESREC);
if (data. IndexOf ("<EOF>") >-1) {
Break
}
}
Show the data on the console.
Console.WriteLine ("Text Received: {0}", data);
Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes (data);
Handler. Send (msg);
Handler. Shutdown (Socketshutdown.both);
Handler. Close ();
}
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
Console.WriteLine ("\nhit Enter to continue ...");
Console.read ();
}
public static int Main (string[] args) {
Startlistening ();
return 0;
}
}

Asynchronous Client Socket Example


The following example program creates a client that is connected to the server. The client is generated with an asynchronous socket, so it does not suspend execution of the client application while waiting for the server to return 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.Threading;
Using System.Text;
State object to receiving data from remote device.
public class StateObject {
Public Socket worksocket = null; Client socket.
public const int buffersize = 256; Size of receive buffer.
Public byte[] buffer = new Byte[buffersize]; Receive buffer.
Public StringBuilder sb = new StringBuilder ();//Received data string.
}
public class Asynchronousclient {
The port number for the remote device.
Private Const int port = 11000;
ManualResetEvent instances signal completion.
New ManualResetEvent (FALSE);
New ManualResetEvent (FALSE);
New ManualResetEvent (FALSE);
The response from the remote device.
private static String response = String.Empty;
private static void Startclient () {
Connect to a remote device.
try {
Establish the remote endpoint for the socket.
"Host.contoso.com" is the name of the
Remote device.
Iphostentry iphostinfo = dns.resolve ("host.contoso.com");
IPAddress ipaddress = iphostinfo.addresslist[0];
IPEndPoint remoteep = new IPEndPoint (ipaddress, Port);
Create a TCP/IP socket.
Socket client = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, PROTOCOLTYPE.TCP);
Connect to the remote endpoint.
New AsyncCallback (Connectcallback), client);
Connectdone.waitone ();
Send test data to the remote device.
Send (Client, "This is a test<eof>");
Senddone.waitone ();
Receive the response from the remote device.
Receive (client);
Receivedone.waitone ();
Write the response to the console.
Console.WriteLine ("Response Received: {0}", Response);
Release the socket.
Client. Shutdown (Socketshutdown.both);
Client. Close ();
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}
private static void Connectcallback (IAsyncResult ar) {
try {
Retrieve the socket from the state object.
Socket client = (socket) ar. asyncstate;
Complete the connection.
Client. EndConnect (AR);
Console.WriteLine ("Socket connected to {0}",
Client. Remoteendpoint.tostring ());
Signal that the connection has been made.
Connectdone.set ();
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}
private static void Receive (Socket client) {
try {
Create the state object.
StateObject state = new StateObject ();
State.worksocket = client;
Begin receiving the data from the remote device.
Client. BeginReceive (state.buffer, 0, stateobject.buffersize, 0,
New AsyncCallback (ReceiveCallback), state);
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}
private static void ReceiveCallback (IAsyncResult ar) {
try {
From the async state object.
StateObject state = (stateobject) ar. asyncstate;
Socket client = State.worksocket;
Read data from the remote device.
int bytesread = client. EndReceive (AR);
if (Bytesread > 0) {
There might is more data, and so store the "data received so far."
State.sb.Append (Encoding.ASCII.GetString (State.buffer,0,bytesread));
Get the rest of the data.
Client. BeginReceive (state.buffer,0,stateobject.buffersize,0,
New AsyncCallback (ReceiveCallback), state);
} else {
All the data has arrived; Put it in response.
if (State.sb.Length > 1) {
Response = state.sb.ToString ();
}
Signal that all bytes have been received.
Receivedone.set ();
}
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}
private static void Send (Socket client, String data) {
Convert the string data to byte using ASCII encoding.
byte[] Bytedata = Encoding.ASCII.GetBytes (data);
Begin sending the data to the remote device.
Client. BeginSend (bytedata, 0, bytedata.length, 0,
New AsyncCallback (Sendcallback), client);
}
private static void Sendcallback (IAsyncResult ar) {
try {
Retrieve the socket from the state object.
Socket client = (socket) ar. asyncstate;
Complete sending the data to the remote device.
int bytessent = client. Endsend (AR);
Console.WriteLine ("Sent {0} bytes to server.", bytessent);
Signal that all bytes have been sent.
Senddone.set ();
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.