// Basic Socket programming
// Server:
Using System. Net;
Using System. Net. Sockets;
Using System. Text;
Using System. Threading;
Thread mythread;
Socket socket;
// Clear all resources in use.
Protected override void Dispose (bool disposing)
{
Try
{
Socket. Close (); // release resources
Mythread. Abort (); // Abort a thread
}
Catch {}
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
Public static IPAddress GetServerIP ()
{
IPHostEntry ieh = Dns. GetHostByName (Dns. GetHostName ());
Return ieh. AddressList [0];
}
Private void BeginListen ()
{
IPAddress ServerIp = GetServerIP ();
IPEndPoint iep = new IPEndPoint (ServerIp, 8000 );
Socket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
Byte [] byteMessage = new byte [1, 100];
This. label1.Text = iep. ToString ();
Socket. Bind (iep );
// Do
While (true)
{
Try
{
Socket. Listen (5 );
Socket newSocket = socket. Accept ();
NewSocket. Receive (byteMessage );
String sTime = DateTime. Now. tow.timestring ();
String msg = sTime + ":" + "Message from :";
Msg + = newSocket. RemoteEndPoint. ToString () + Encoding. Default. GetString (byteMessage );
This. listBox1.Items. Add (msg );
}
Catch (SocketException ex)
{
This. label1.Text + = ex. ToString ();
}
}
// While (byteMessage! = Null );
}
// Start listening
Private void button#click (object sender, System. EventArgs e)
{
Try
{
Mythread = new Thread (new ThreadStart (BeginListen ));
Mythread. Start ();
}
Catch (System. Exception er)
{
MessageBox. Show (er. Message, "finished", MessageBoxButtons. OK, MessageBoxIcon. Stop );
}
}
// Client:
Using System. Net;
Using System. Net. Sockets;
Using System. Text;
Private void button#click (object sender, System. EventArgs e)
{
BeginSend ();
}
Private void BeginSend ()
{
String ipdomainthis.txt ip. Text;
String portdeskthis.txt port. Text;
IPAddress serverIp = IPAddress. Parse (ip );
Int serverPort = Convert. ToInt32 (port );
IPEndPoint iep = new IPEndPoint (serverIp, serverPort );
Byte [] byteMessage;
// Do
//{
Socket socket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
Socket. Connect (iep );
ByteMessage = Encoding. ASCII. GetBytes (textBox1.Text );
Socket. Send (byteMessage );
Socket. Shutdown (SocketShutdown. Both );
Socket. Close ();
//}
// While (byteMessage! = Null );
}
Transmission and receiving end based on TCP protocol
TCP Receiver
Using System. Net. Sockets; // use the TcpListen class
Using System. Threading; // use the thread
Using System. IO; // use StreamReader class
Int port = 8000; // define the listening port number
Private Thread thThreadRead; // creates a Thread to listen on the port number and receive information.
Private TcpListener tlTcpListen; // listener port number
Private bool blistener = true; // sets the flag bit to determine the listening status
Private NetworkStream nsStream; // create the received basic data stream
Private StreamReader srRead;
Private System. Windows. Forms. StatusBar statusBar1;
Private System. Windows. Forms. Button button1;
Private System. Windows. Forms. ListBox listBox1; // read data from the basic network data stream
Private TcpClient tcClient;
Private void Listen ()
{
Try
{
TlTcpListen = new TcpListener (port); // initialize the TcpListener instance on the port 8000
TlTcpListen. Start (); // Start listening
StatusBar1.Text = "listening ";
TcClient = tlTcpListen. AcceptTcpClient (); // TCP Connection Request
NsStream = tcClient. GetStream (); // obtain the basic network data stream used to send and receive data
SrRead = new StreamReader (nsStream); // obtains the basic network data stream to initialize the StreamReader instance.
StatusBar1.Text = "connected! ";
While (blistener) // loop listener
{
String sMessage = srRead. ReadLine (); // read a row of data from the basic network data stream
If (sMessage = "STOP") // determines whether the TCP Connection Control code is disconnected.
{
TlTcpListen. Stop (); // disable listening
NsStream. Close (); // release resources
SrRead. Close ();
StatusBar1.Text = "the connection has been closed! ";
ThThreadRead. Abort (); // Abort a thread
Return;
}
String sTime = DateTime. Now. tow.timestring (); // the time when the data is received.
ListBox1.Items. Add (sTime + "" + sMessage );
}
}
Catch (System. Security. SecurityException)
{
MessageBox. Show ("failed to listen! "," Error ");
}
}
// Start listening
Private void button#click (object sender, System. EventArgs e)
{
ThThreadRead = new Thread (new ThreadStart (Listen ));
ThThreadRead. Start (); // Start the thread
Button1.Enabled = false;
}
// Clear all resources in use.
Protected override void Dispose (bool disposing)
{
Try
{
TlTcpListen. Stop (); // disable listening
NsStream. Close ();
SrRead. Close (); // release resources
ThThreadRead. Abort (); // Abort a thread
}
Catch {}
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
Sending end of TCP protocol
Using System. Net. Sockets; // use the TcpListen class
Using System. Threading; // use the thread
Using System. IO; // use StreamWriter class
Using System. Net; // use the IPAddress class and IPHostEntry class.
Private StreamWriter swWriter; // used to transmit data to the basic network data stream
Private NetworkStream nsStream; // create the network-based data stream for data transmission
Private TcpClient tcpClient;
Private System. Windows. Forms. Button button1;
Private System. Windows. Forms. TextBox textBox1;
Private System. Windows. Forms. Button button2;
Private System. Windows. Forms. TextBox textBox2;
Private System. Windows. Forms. StatusBar statusBar1;
Private System. Windows. Forms. Label label1;
Private System. Windows. Forms. Label label2; // submit a TCP connection request to the remote host.
Private bool tcpConnect = false; // defines the identifier to indicate whether a TCP connection is established.
// Connection
Private void button#click (object sender, System. EventArgs e)
{
IPAddress ipRemote;
Try
{
IpRemote = IPAddress. Parse (textBox1.Text );
}
Catch // determine the validity of a given IP Address
{
MessageBox. Show ("The Entered IP address is invalid! "," Error message! ");
Return;
}
IPHostEntry ipHost;
Try
{
IpHost = Dns. Resolve (textBox1.Text );
}
Catch // determine whether the host corresponding to the IP address is online
{
MessageBox. Show ("the remote host is not online! "," Error message! ");
Return;
}
String sHostName = ipHost. HostName;
Try
{
TcpClient tcpClient = new TcpClient (sHostName, 8000); // apply for a TCP connection to port 8000 of the remote host
NsStream = tcpClient. GetStream (); // obtain the basic network data stream for data transmission through application
SwWriter = new StreamWriter (nsStream); // use the obtained basic network data stream to initialize the StreamWriter instance.
Button1.Enabled = false;
Button2.Enabled = true;
TcpConnect = true;
StatusBar1.Text = "connected! ";
}
Catch
{
MessageBox. Show ("cannot establish a connection with the remote host port 8000! "," Error message! ");
Return;
}
}
// Send
Private void button2_Click (object sender, System. EventArgs e)
{
If (textBox2.Text! = "")
{
SwWriter. WriteLine (textBox2.Text); // refresh the data in the current data stream
SwWriter. Flush ();
}
Else
{
MessageBox. Show ("The message cannot be blank! "," Error message! ");
}
}
// Clear all resources in use.
Protected override void Dispose (bool disposing)
{
If (tcpConnect)
{
SwWriter. WriteLine ("STOP"); // send control code
SwWriter. Flush (); // refresh the data in the current data stream
NsStream. Close (); // clear Resources
SwWriter. Close ();
}
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
-From happy pig's column