1// File Name GreetingServer.java
2import java.net.*;
3import java.io.*;
4
5public class GreetingServer extends Thread {
6 private ServerSocket serverSocket;
7
8 public GreetingServer(int port) throws IOException {
9 serverSocket = new ServerSocket(port);
10 serverSocket.setSoTimeout(10000);
11 }
12
13 public void run() {
14 while(true) {
15 try {
16 System.out.println("Waiting for client on port " +
17 serverSocket.getLocalPort() + "...");
18 Socket server = serverSocket.accept();
19
20 System.out.println("Just connected to " + server.getRemoteSocketAddress());
21 DataInputStream in = new DataInputStream(server.getInputStream());
22
23 System.out.println(in.readUTF());
24 DataOutputStream out = new DataOutputStream(server.getOutputStream());
25 out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
26 + "\nGoodbye!");
27 server.close();
28
29 } catch (SocketTimeoutException s) {
30 System.out.println("Socket timed out!");
31 break;
32 } catch (IOException e) {
33 e.printStackTrace();
34 break;
35 }
36 }
37 }
38
39 public static void main(String [] args) {
40 int port = Integer.parseInt(args[0]);
41 try {
42 Thread t = new GreetingServer(port);
43 t.start();
44 } catch (IOException e) {
45 e.printStackTrace();
46 }
47 }
48}
1// File Name GreetingClient.java
2import java.net.*;
3import java.io.*;
4
5public class GreetingClient {
6
7 public static void main(String [] args) {
8 String serverName = args[0];
9 int port = Integer.parseInt(args[1]);
10 try {
11 System.out.println("Connecting to " + serverName + " on port " + port);
12 Socket client = new Socket(serverName, port);
13
14 System.out.println("Just connected to " + client.getRemoteSocketAddress());
15 OutputStream outToServer = client.getOutputStream();
16 DataOutputStream out = new DataOutputStream(outToServer);
17
18 out.writeUTF("Hello from " + client.getLocalSocketAddress());
19 InputStream inFromServer = client.getInputStream();
20 DataInputStream in = new DataInputStream(inFromServer);
21
22 System.out.println("Server says " + in.readUTF());
23 client.close();
24 } catch (IOException e) {
25 e.printStackTrace();
26 }
27 }
28}
1public class GreetServer {
2 private ServerSocket serverSocket;
3 private Socket clientSocket;
4 private PrintWriter out;
5 private BufferedReader in;
6
7 public void start(int port) {
8 serverSocket = new ServerSocket(port);
9 clientSocket = serverSocket.accept();
10 out = new PrintWriter(clientSocket.getOutputStream(), true);
11 in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
12 String greeting = in.readLine();
13 if ("hello server".equals(greeting)) {
14 out.println("hello client");
15 }
16 else {
17 out.println("unrecognised greeting");
18 }
19 }
20
21 public void stop() {
22 in.close();
23 out.close();
24 clientSocket.close();
25 serverSocket.close();
26 }
27 public static void main(String[] args) {
28 GreetServer server=new GreetServer();
29 server.start(6666);
30 }
31}