Server programs
Using System;
Using System. Net;
Using System. Net. Sockets;
Using System. Text;
Namespace SocketServer
{
/// <Summary>
/// Summary of Class1.
/// </Summary>
Class Class1
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
// Define the port number
Private const int porNum = 81;
[STAThread]
Static void Main (string [] args)
{
//
// TODO: Add code here to start the application
//
Bool done = false;
TcpListener listener = new TcpListener (porNum );
Listener. Start ();
While (! Done ){
Console. Write ("listening for port 81 ...");
TcpClient client = listener. AcceptTcpClient ();
Console. WriteLine ("\ n processing connection requests ...");
NetworkStream ns = client. GetStream ();
// Ns. Read (, 0 ,);
Byte [] bytes = new byte [1, 1024];
Int bytesRead = ns. Read (bytes, 0, bytes. Length );
Console. WriteLine (Encoding. BigEndianUnicode. GetString (bytes, 0, bytesRead ));
Byte [] byteTime = Encoding. ASCII. GetBytes (DateTime. Now. ToString ());
Try
{
Ns. Write (byteTime, 0, byteTime. Length );
Ns. Close ();
Client. Close ();
}
Catch (Exception ex ){
Console. WriteLine (ex. ToString ());
}
}
Listener. Stop ();
}
}
}
Web Client
Add a namespace:
Using System. Net;
Using System. Net. Sockets;
Using System. Text;
Connection code:
Private void socketButton_Click (object sender, System. EventArgs e)
{// Connect to the server program
Try
{
// Start the connection
TcpClient client = new TcpClient ("192.168.0.100", 81 );
NetworkStream ns = client. GetStream ();
Byte [] byteTime = Encoding. BigEndianUnicode. GetBytes ("client data submission \ n ");
Ns. Write (byteTime, 0, byteTime. Length );
// Return client information
Byte [] clientIp = Encoding. BigEndianUnicode. GetBytes ("Client IP Address:" + Request. UserHostAddress + "\ n ");
Ns. Write (clientIp, 0, clientIp. Length );
Byte [] bytes = new byte [1, 1024];
Int bytesRead = ns. Read (bytes, 0, bytes. Length );
ShowLabel. Text = "server return information" + Encoding. ASCII. GetString (bytes, 0, bytesRead );
Client. Close ();
}
Catch (Exception ex)
{
ShowLabel. Text = "throwing an exception" + ex. ToString ();
}
Finally {}
}