This program enables us to chat between the client and server. This is a bidirectional data transfer.
Client
import java.io.*;
import java.net.*;
import java.util.*;
class Client
{
public static void main(String arghs[])
{
try
{
Socket clientskt=new Socket("127.0.0.1",1024);
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
DataInputStream din=new DataInputStream(clientskt.getInputStream());
DataOutputStream dout=new DataOutputStream(clientskt.getOutputStream());
System.out.print("You have to type:");
String str=in.readLine();
dout.writeBytes(str+"\n");
if(str.equals("bye"))
{
break;
}
String str1=din.readLine();
System.out.println("Server:"+str1);
if(str1.equals("bye"))
{
break;
}
}
clientskt.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
SERVER
import java.io.*;
import java.net.*;
import java.util.*;
class Server
{
public static void main(String args[])
{
try
{
ServerSocket sock=new ServerSocket(1024);
Socket clientskt=sock.accept();
while(true)
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
DataInputStream din=new DataInputStream(clientskt.getInputStream());
DataOutputStream dout=new DataOutputStream(clientskt.getOutputStream());
String str1=din.readLine();
System.out.println("Client:"+str1);
if(str1.equals("bye"))
{
break;
}
System.out.print("You have to type:");
String str=in.readLine();
dout.writeBytes(str+'\n');
if(str.equals("bye"))
{
break;
}
}
sock.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output
E:\java>javac Server.java
E:\java>java Client
E:\java>java Client
You have to type:hai
Server:hello
You have to type:how r u
Server:fine u?
You have to type:fine
Server:r u free?
You have to type:bye
E:\java>java Server
Client:hai
You have to type:hello
Client:how r u
You have to type:fine u?
Client:fine
You have to type:r u free?
Client:bye
No comments:
Post a Comment