This is a simple example of socket programming using TCPListener and TCP client. Compile and run the server and client programs after the changing the IP addresses in the programs to the machine from which the server is going to run.
CLIENT.CS:
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class clnt {
public static void Main() {
try {
TcpClient? tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.0.2",8001); // use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba,0,ba.Length);
byte[] bb=new byte100;
int k=stm.Read(bb,0,100);
for (int i=0;i k;i++)
Console.Write(Convert.ToChar(bbi));
tcpclnt.Close();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
SERVER.CS:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class serv {
public static void Main() {
try {
IPAddress ipAd = IPAddress.Parse("192.168.0.2"); //use local m/c IP address, and use the same in the client
TcpListener? myList=new TcpListener(ipAd,8001);
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" + myList.LocalEndpoint );
Console.WriteLine("Waiting for a connection.....");
Socket s=myList.AcceptSocket();
Console.WriteLine("Connection accepted from "+s.RemoteEndPoint);
byte[] b=new byte100;
int k=s.Receive(b);
Console.WriteLine("Recieved...");
for (int i=0;i k;i++)
Console.Write(Convert.ToChar(bi));
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\\nSent Acknowledgement");
s.Close();
myList.Stop();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
0 comments:
Post a Comment