Use. NET access to the Internet (5) Paul

Source: Internet
Author: User
Tags bind continue socket string back thread tostring
Access

Asynchronous server Sockets sample


The following example program creates a server that receives connection requests from clients. The server is generated with an asynchronous 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;
Using System.Threading;
State object for reading client data asynchronously
public class StateObject {
Public Socket worksocket = null; Client socket.
public const int buffersize = 1024; Size of receive buffer.
Public byte[] buffer = new Byte[buffersize]; Receive buffer.
Public StringBuilder sb = new StringBuilder (); Received data string.
}
public class Asynchronoussocketlistener {
Incoming data from client.
public static string data = NULL;
Thread signal.
public static ManualResetEvent alldone = new ManualResetEvent (false);
Public Asynchronoussocketlistener () {
}
public static void Startlistening () {
Data buffer for incoming data.
byte[] bytes = new byte[1024];
Establish the local endpoint for the socket.
The DNS name of the computer
Running the listener is "host.contoso.com".
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);
Bind the socket to the "local endpoint" and listen for incoming connections.
try {
Listener. Bind (Localendpoint);
Listener. Listen (100);
while (true) {
Set the event to nonsignaled state.
Alldone.reset ();
Start a asynchronous socket to listen for connections.
Console.WriteLine ("Waiting for a Connection ...");
New AsyncCallback (Acceptcallback),
Listener);
Wait until a connection is made before continuing.
Alldone.waitone ();
}
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
Console.WriteLine ("\nhit Enter to continue ...");
Console.read ();
}
public static void Acceptcallback (IAsyncResult ar) {
Signal the main thread to continue.
Alldone.set ();
Get the socket that handles the client request.
Socket listener = (socket) ar. asyncstate;
Socket handler = listener. Endaccept (AR);
Create the state object.
StateObject state = new StateObject ();
State.worksocket = handler;
Handler. BeginReceive (state.buffer, 0, stateobject.buffersize, 0,
New AsyncCallback (Readcallback), state);
}
public static void Readcallback (IAsyncResult ar) {
String content = String.Empty;
Retrieve the state object and the handler socket
From the async state object.
StateObject state = (stateobject) ar. asyncstate;
Socket handler = State.worksocket;
int bytesread = handler. 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));
More data.
Content = State.sb.ToString ();
if (content). IndexOf ("<EOF>") >-1) {
Client. Display it on the console.
Console.WriteLine ("Read {0} bytes from socket.") \ n Data: {1} ",
Content. Length, content);
Echo the data back to the client.
Send (handler, content);
} else {
Not all data received. Get more.
Handler. BeginReceive (state.buffer, 0, stateobject.buffersize, 0,
New AsyncCallback (Readcallback), state);
}
}
}
private static void Send (Socket handler, 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.
Handler. BeginSend (bytedata, 0, bytedata.length, 0,
New AsyncCallback (Sendcallback), handler);
}
private static void Sendcallback (IAsyncResult ar) {
try {
Retrieve the socket from the state object.
Socket handler = (socket) ar. asyncstate;
Complete sending the data to the remote device.
int bytessent = handler. Endsend (AR);
Console.WriteLine ("Sent {0} bytes to client.", bytessent);
Handler. Shutdown (Socketshutdown.both);
Handler. Close ();
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}
public static int Main (string[] args) {
Startlistening ();
return 0;
}
}
best practices for using Net classes
The following recommendations will help you make the most effective use of System.NetClasses contained in:
    • Use WebRequest and WebResponse instead of a type to convert to a descendant class whenever possible. Applications using WebRequest and WebResponse can take advantage of new Internet protocols without requiring a wide range of code changes.
    • When you write a asp.net application running on a server using the System.Net class, asynchronous methods that use GetResponse and getresponsestream are generally better from a performance point of view.
    • The number of connections opened to Internet resources may have a significant impact on network performance and throughput. By default,System.Net uses two connections for each application for each host. Setting the Connectionlimit property in the application's ServicePoint can increase this number for a specific host. Set the Servicepointmanager.defaultpersistentconnectionlimit property to add this default value for all hosts.
    • When writing a socket-level protocol, try to use tcpclient or udpclient whenever possible, rather than writing directly to the socket. These two client classes encapsulate the creation of TCP and UDP sockets without requiring you to handle the details of the connection.
    • When accessing sites that require credentials, use the CredentialCache class to create a cache of credentials instead of providing them for each request. The CredentialCache class searches the cache to find the appropriate credentials to provide to the request, so that you do not have to create and provide credentials based on the Uniform Resource Locator.
Summary
Here are some basic concepts and code examples of. NET access to the Internet in vs.net (including various methods and steps to access the Internet) for your reference. Have any suggestions please mail me paulni@citiz.net (paulni@citiz.net).

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.