Synchronous client sleeve
The following sample program creates a client connected to the server. The client is generated with synchronization sockets, so hangs the execution of the client application until the server returns. The application sends a string to the server and then displays the string returned by the server.
[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
// dend 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 ("Argumentnullexce: {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;
}
}
Synchronous server socket
The following sample program creates a server that receives a connection request from the client. The server is generated with synchronization sockets, so do not suspend the execution of the server application when waiting for a connection from the client. The app receives a string from the client, displays the string, and then displays the string back to the client. Strings from the client must contain strings
[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 startlistence () {
// Data Buffer for incoming data.
Byte [] bytes = new byte [1024];
// establish the local endpoint for the socket.
// dns.gethostname returns the name of there
// 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;
// bind the socket to the local endpoint and
// Listen for incoming connection.
Try {
Listener.bind (localendpoint);
Listener.listen (10);
// Start Listening for Connections.
While (true) {
Console.WriteLine ("Waiting for a connection ...");
// Program Is Suspended While Waiting for An Incoming Connection.
Socket handler = listener.accept ();
Data = NULL;
// an incoming connection needed.
While (true) {
BYtes = New byte [1024];
INT BYTESREC = Handler.Receive (Bytes);
Data = encoding.ascii.getstring (bytes, 0, bytesrec);
IF (Data.Indexof ("
}
}
// 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 sleeve
The following sample program creates a client connected to the server. This client is generated with asynchronous sockets, so the client application is not suspended when the server returns a response. The application sends a string to the server and then displays the string returned by the server.
[C #]
Using system;
Using system.net;
Using system.net.sockets;
Using system.threading;
Using system.text;
// State Object For Receiving Data from Remote Device.
Public class stateObject {
Public Socket Worksocket = null; // Client Socket.
Public const Int buffersize = 256; // size of receiving 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;
// ManualReveTevent Instances Signal Completion.
Private static manualRetevent connectDone =
New ManualRetevent (false);
Private static manualRest Senddone =
New ManualRetevent (false);
Private static manualReveTevent ReceiveDone =
New ManualRetevent (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.
Client.beginconnect (remoteep,
New asyncCallback (ConnectCallback), Client;
ConnectDone.waitone ();
// send test data to the remote defices.
Send (Client, "This Is A Test
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.buffearsize, 0,
New asyncCallback, State);} catch (exception e) {
Console.writeLine (E.TOString ());
}
}
Private Static Void ReceiveCallback (IASYNCRESULT AR) {
Try {
// Retrieve The State Object and The Client Socket
// 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 Be More Data, 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.buffearsize, 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 Alltes 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 data 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 Alltes Have Been Sent.
Senddone.set ();
} catch (exception e) {
Console.writeLine (E.TOString ());
}
}
Public static int main (string [] args) {
STARTCLIENT ();
Return 0;
}
}
Asynchronous server socket
The following sample program creates a server that receives a connection request from the client. The server is generated with asynchronous sockets, so the execution of the server application is not suspended when waiting for a connection from the client. The app receives a string from the client, displays the string, and then displays the string back to the client. Strings from the client must contain strings
[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 recene buffer.
Public Byte [] buffer = new byte [buffersize]; // receive buffer.
Public StringBuilder SB = new stringbuilder (); // received data string.
}
Public class asynchronoussocketlistener {
// incoming data from cliant.
Public static string data = NULL;
// Thread Signal.
Public Static ManualReveTevent Alldone = New ManualReveTevent (false);
Public asynchronoussocketlistener () {
}
Public static void startlistence () {
// 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 incnections.
Try {
Listener.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),
Listener;
// Wait Until a connection is master before continaing.
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.ndAccept (AR);
// CREATE The State Object.
StateObject State = new stateObject ();
State.worksocket = handler;
Handler.BeginReceive (state.buffer, 0, stateObject.buffearsize, 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;
// ingd data from the client socket.
INT BYTESREAD = Handler.Endreceive (ar);
IF (BytesRead> 0) {
// There Might Be More Data, So Store The Data Received So Far.
State.sb.append (encoding.ascii.getstring)
State.buffer, 0, BytesRead);
// check for end-of-file tag. If it is not there, read
// More data.
Content = state.sb.tostring ();
IF (content.indexof ("
// all the data haas been read from the
// 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.buffearsize, 0,
New asyncCallback (READCALLBACK), STATE);
}
}
}
Private static void send (socket handler, string data) {
// Convert the string data to byte data 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 practice using NET classes
The following suggestions will help you use the classes contained in System.net:
Use WebRequest and WebResponse as much as possible instead of the type to be converted into sub-generation. Using WebRequest and WebResponse applications can utilize new Internet protocols without having to make a wide range of code changes.
When writing an ASP.NET application running on the server using the System.NET class, use the asynchronous methods of using getResponse and getResponseSstream from performance perspectives.
The number of connections open to the Internet resource may have a significant impact on network performance and throughput. By default, System.NET uses two connections to each application of each host. Setting the ConnectionLimit property in ServicePoint in the application to add this number to a particular host. Setting ServicePointManager.defaultPersistentConnectionLimit properties to add this default value for all hosts.
When writing a socket level protocol, try using TcpClient or UDPClient as much as possible instead of writing to the socket directly. These two client classes encapsulate TCP and UDP sockets, without requiring the details of your connection. When accessing the required credentials, use the CredentialCache class to create credentials without providing them for each request. CredentialCache class Search Cache to find appropriate credentials to be provided to request, so you don't have to create and provide credentials according to the unified resource locator.
to sum up
The above is some of the basic concepts and code examples of .NET access to the Internet (including access to the Internet), give you a reference. If you have any suggestions, please Mil I Paulni@citiz.net.