* 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 ;
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.
|