Tuesday, September 20, 2011

Intercommunication Process Using TCP

//Here is the method to send some strings through a port

// Create a new instance of TCPListener and indicate the port
TcpListener l = new TcpListener(1001);
// Start Listener
l.Start();
// wait for client to make request
TcpClient c = l.AcceptTcpClient(); 
// access steam to send data to client.
NetworkStream ns = c.GetStream(); 

// get system date and convert it to string
string st = txtSend.Text; 

//convert string to an array of Bytes
byte[] buf = System.Text.Encoding.ASCII.GetBytes(st); 
//write to stream
ns.Write(buf, 0, st.Length);

// Stop Listener
l.Stop();

//Here is the method to Receive some strings through a port

// Create a new instance of TCPClient and indicate the port
TcpClient c = new TcpClient("localhost", 1001);

// get stream
NetworkStream ns = c.GetStream(); 

// create byte array to receive data
byte[] buf = new byte[100];  

//read data from stream into byte array
ns.Read(buf, 0, 100);
// convert byte array to string
string st = System.Text.Encoding.ASCII.GetString(buf);


        

No comments:

Post a Comment