Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Friday 20 January 2017

java program to establish connection between server and client.

--------------------------------for Client-----------------------

import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args )
{
String hostname="127.0.0.1";
int portNumber=9991;
try
{


Socket echoSocket=new Socket(hostname,portNumber);
PrintWriter out=new PrintWriter(echoSocket.getOutputStream(),true);
BufferedReader in=new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));

BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput=stdIn.readLine()) !=null)
{
out.println(userInput);
System.out.println("ëcho: " + in.readLine());
}
echoSocket.close();
}catch(Exception e)
{
System.out.println("exception occured  :" + e);
}

}
}

-------------------------------------for Server------------------------------


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

int portNumber=9991;

ServerSocket echoServerSocket=new ServerSocket(portNumber);
Socket s1=echoServerSocket.accept();
PrintWriter out=new PrintWriter(s1.getOutputStream(),true);
BufferedReader in=new BufferedReader(new InputStreamReader(s1.getInputStream()));

BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput=in.readLine()) !=null)
{
out.println(userInput);
System.out.println("ëcho: " + in.readLine());
}
echoServerSocket.close();
}
}
--------------------------------------

No comments:

Post a Comment