Client Server program in java

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 );
}}}}}
/*
Client Server program in java OUTPUT:
change local host to ip address of client and server to implement on two computers

Client Server program in java 1

Client Server program in java 1

tcp socket programming in java

tcp socket programming in java

Facing difficulties in understanding the program ?

Ask Your Queries in Comment Box

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *