Wednesday, October 18, 2006

Using TCP to communicate


So you want to communicate to another computer via your local TCP network?

One of the computers needs to be listening (System.Net.Sockets.TcpListener), this is oftne refered to as the server.

Another computer needs to be broadcasting (System.Net.Sockets.TcpClient), often refered to as the client.

If a connection is established between the server and the client then they can communicate via the System.Net.Sockets.NetworkStream class.

TCP is reliable, connection oriented protocol. Has built in flow control, sequencing and error handling.

SERVER SAMPLE CODE

TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"),8000);
listener.Start();
using(TcpClient client=listener.AcceptTcpClient()){
--NetworkStream stream = client.GetStream();
--using(BinaryWriter w = new BinaryWriter(stream)){
----using(BinaryReader r = new BinaryReader(stream)){
------ if(r.ReadString() == "Hello"){
--------w.Write("OK");
--------while(r.ReadString()!="Bye"){}
------}
----}
--}
}

listener.Stop();



CLIENT SAMPLE CODE

The client port is assigned dynamically by default (it is chosen dynamically at runtime from the available ports)

using System.IO;
using System.Net;
using System.Net.Sockets;


TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("127.0.0.1"),8000);
NetworkStream stream = client.GetStream();
--using(BinaryWriter w = new BinaryWriter(stream)){
----using(BinaryReader r = new BinaryReader(stream)){
------w.Write("Hello");
------if(r.ReadString()=="OK"){
--------w.Write("Bye");
------}
----}
--}

client.Close();

No comments: