Pages

Make your own Tcp Server/ Client

tcp-ip




    In this tutorial I’m going to show you how to make a tcp server with C#. If you ever work with windows’ sockets , you already know how difficult this can sometimes be. However you can see how it can be easy in .net platform.

* firstly you must add which name space you need for network programming.
using System.Net;
using System.Net.Sockets;
And then you can write this code ;

image  
Now Just start to explain our code.In main function you just define your class instance which name is Initialize and use it’s method which is called StartListen.And in this method we just  called the StartStream method firstly.
At the StartStream method our first work is defining  our variable.After this We must send parameter to TcpListener object what it needs.
*newsock = new TcpListener(IPAddress.Any, Convert.ToInt32(port));    => here we define ip adres and port for listener.
*newsock.Start();   =>
Just started our TcpListener.
*client = newsock.AcceptTcpClient();   =>  this code part is blocking until a client is connected to the  server and accepts a pending connection request.
*ns = client.GetStream();   => set our networkStream to send or receive data. 
* In the StartListen method, you define byte array and use networkstream write method.
byte[] dizi = Encoding.ASCII.GetBytes(LA);  
ns.Write(dizi, 0, dizi.Length);  

Attention ! please dont forget to close your stream after all works are  over.Like these =>   
newsock.Stop();  client.Close(); ns.close();


At client side, you can use this code block for read data from tcpserver. And you can find explanation about every statement why we use it.


byte [] data = new byte[1024];
//this line is about reading data from networkstream
// and just for learning to find how many byte we use in array which name is ‘data’
recv = ns.Read(data, 0, data.Length);
//at here, we convert our data type byte to string  
string ss = Encoding.ASCII.GetString(data, 0, recv);
// after this line you can do what you want …

Hiç yorum yok: