Client Server > Java Program

Computer Networks



Client Server > Java Program


TCPClient.java File

import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{


String FromServer;
String ToServer;
Socket clientSocket = new Socket(“localhost”, 5000);
BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while (true)
{
FromServer = inFromServer.readLine();
if ( FromServer.equals(“q”) || FromServer.equals(“Q”))
{
clientSocket.close();
break;
}
else
{
System.out.println(“RECIEVED:\t” + FromServer);
System.out.print(“SEND :\t”);
ToServer = inFromUser.readLine();

if (ToServer.equals(“Q”) || ToServer.equals(“q”))
{
outToServer.println (ToServer) ;
clientSocket.close();
break;
}
else
outToServer.println(ToServer);
}
}
}
}

TCPServer.java File

import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String fromclient;
String toclient;
ServerSocket Server = new ServerSocket (5000);
System.out.println (“TCPServer Waiting for client on port 5000″);
while(true)
{
Socket connected = Server.accept();
System.out.println( ” THE CLIENT”+” “+
connected.getInetAddress() +”:”+connected.getPort()+” IS CONNECTED “);
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader (connected.getInputStream()));
PrintWriter outToClient =
new PrintWriter(
connected.getOutputStream(),true);
while ( true )
{
System.out.print(“SEND :\t”);
toclient = inFromUser.readLine();
if ( toclient.equals (“q”) || toclient.equals(“Q”) )
{
outToClient.println(toclient);
connected.close();
break;
}
else
{
outToClient.println(toclient);
}
fromclient = inFromClient.readLine();
if ( fromclient.equals(“q”) || fromclient.equals(“Q”) )
{
connected.close();
break;
}
else
{
System.out.println( “RECIEVED:\t” + fromclient );
}
}
}
}
}

Comments

Popular posts from this blog

Intermediate Code Generation > C Program