
Java Client-Server Example
Server
Here is a short example of a server written in Java. You will find the matching client further down in the page.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerExample {
public void startItUp(){
ServerSocket aServerSocket = null;
try {
aServerSocket = new ServerSocket(7070);
} catch (IOException e1) {
e1.printStackTrace();
return;
}
boolean keepGoing = true;
while(keepGoing){
try {
System.out.println("Waiting for connection.");
Socket aClientSocket = aServerSocket.accept();
System.out.println("Connection made from a client.");
BufferedReader fromClient = new BufferedReader(
new InputStreamReader(aClientSocket.getInputStream()));
PrintWriter toClient = new PrintWriter(aClientSocket.getOutputStream(),
true);
String messageString = null;
while((messageString = fromClient.readLine()) != null){
String responseString = messageString + " -------Is this for real?-------";
toClient.println(responseString);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ServerExample aServer = new ServerExample();
aServer.startItUp();
}
}
Client
Here is the client code that goes with the server shown above.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientExample {
public void talkBack(){
BufferedReader fromUser = new BufferedReader(
new InputStreamReader(System.in));
Socket aSocket = null;
PrintWriter toServer = null;
BufferedReader fromServer = null;
try {
System.out.println("Connecting.");
aSocket = new Socket("localhost", 7070);
fromServer = new BufferedReader(
new InputStreamReader(aSocket.getInputStream()));
toServer = new PrintWriter(aSocket.getOutputStream(),
true);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
System.out.println("Connected.\n\nPlease enter a string to to send to the server:\n");
String fromUserString = null;
try{
while((fromUserString = fromUser.readLine()) != null){
toServer.println(fromUserString);
String result = fromServer.readLine();
System.out.println(result);
}
}
catch(Exception e){
e.printStackTrace();
return;
}
}
public static void main(String[] args) {
ClientExample aClient = new ClientExample();
aClient.talkBack();
System.out.println("\n\n\nDone.");
}
}