Program for chatting using TCP Protocol
Server Code:
import java.io.*;
import java.net.*;
import java.util.*;
class tcpchs
{
public static void main(String ar[]) throws Exception
{
String clsent,ssent;
ServerSocket wsoc=new ServerSocket(3232);
Socket ssoc=wsoc.accept();
BufferedReader ifc=new BufferedReader(new InputStreamReader(ssoc.getInputStream()));
BufferedReader ifs=new BufferedReader(new InputStreamReader(System.in));
DataOutputStream otc=new DataOutputStream(ssoc.getOutputStream());
while(true)
{
clsent=ifc.readLine();
if(clsent.equals("exit"))
{break;}
System.out.println("From Client: "+clsent);
ssent=ifs.readLine();
otc.writeBytes(ssent+'\n');
}
ssoc.close();
}
}
Client Code:
import java.io.*;
import java.net.*;
import java.util.*;
class tcpchc
{
public static void main(String ar[]) throws Exception
{
String clsent,ssent;
Socket ssoc=new Socket("localhost",3232);
BufferedReader ifs=new BufferedReader(new InputStreamReader(ssoc.getInputStream()));
BufferedReader ifc=new BufferedReader(new InputStreamReader(System.in));
DataOutputStream ots=new DataOutputStream(ssoc.getOutputStream());
while(true)
{
clsent=ifc.readLine();
ots.writeBytes(clsent+'\n');
ssent=ifs.readLine();
if(ssent.equals("exit"))
break;
System.out.println("From Server: "+ssent);
}
ssoc.close();
}
}
Output for client and server:
Server Code:
import java.io.*;
import java.net.*;
import java.util.*;
class tcpchs
{
public static void main(String ar[]) throws Exception
{
String clsent,ssent;
ServerSocket wsoc=new ServerSocket(3232);
Socket ssoc=wsoc.accept();
BufferedReader ifc=new BufferedReader(new InputStreamReader(ssoc.getInputStream()));
BufferedReader ifs=new BufferedReader(new InputStreamReader(System.in));
DataOutputStream otc=new DataOutputStream(ssoc.getOutputStream());
while(true)
{
clsent=ifc.readLine();
if(clsent.equals("exit"))
{break;}
System.out.println("From Client: "+clsent);
ssent=ifs.readLine();
otc.writeBytes(ssent+'\n');
}
ssoc.close();
}
}
Client Code:
import java.io.*;
import java.net.*;
import java.util.*;
class tcpchc
{
public static void main(String ar[]) throws Exception
{
String clsent,ssent;
Socket ssoc=new Socket("localhost",3232);
BufferedReader ifs=new BufferedReader(new InputStreamReader(ssoc.getInputStream()));
BufferedReader ifc=new BufferedReader(new InputStreamReader(System.in));
DataOutputStream ots=new DataOutputStream(ssoc.getOutputStream());
while(true)
{
clsent=ifc.readLine();
ots.writeBytes(clsent+'\n');
ssent=ifs.readLine();
if(ssent.equals("exit"))
break;
System.out.println("From Server: "+ssent);
}
ssoc.close();
}
}
Output for client and server:
0 comments:
Post a Comment