Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Multi-threaded Echo Server and Client in Java

Client Program:-

  1.  
  2. import java.net.*;
  3. import java.io.*;
  4.  
  5. class Client {
  6.  
  7. public static void main(String args[]) throws IOException {
  8. Socket soc = null;
  9. String str = null;
  10. BufferedReader br = null;
  11. DataOutputStream dos = null;
  12. BufferedReader kyrd = new BufferedReader(new InputStreamReader(System.in));
  13. try {
  14. soc = new Socket(InetAddress.getLocalHost(), 95);
  15. br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
  16. dos = new DataOutputStream(soc.getOutputStream());
  17. } catch (UnknownHostException uhe) {
  18. System.out.println("Unknown Host");
  19. System.exit(0);
  20. }
  21. System.out.println("To start the dialog type the message in this client window \n Type exit to end");
  22. boolean more = true;
  23. while (more) {
  24. str = kyrd.readLine();
  25. dos.writeBytes(str);
  26. dos.write(13);
  27. dos.write(10);
  28. dos.flush();
  29. String s, s1;
  30. s = br.readLine();
  31. System.out.println("From server :" + s);
  32. if (s.equals("exit")) {
  33. break;
  34. }
  35. }
  36. br.close();
  37. dos.close();
  38. soc.close();
  39. }
  40. }



Server Program
  1. import java.net.*;
  2. import java.io.*;
  3.  
  4. class Server {
  5.  
  6. public static void main(String args[]) throws IOException {
  7. ServerSocket ss = null;
  8. try {
  9. ss = new ServerSocket(95);
  10. } catch (IOException ioe) {
  11. System.out.println("Error finding port");
  12. System.exit(1);
  13. }
  14. Socket soc = null;
  15. try {
  16. soc = ss.accept();
  17. System.out.println("Connection accepted at :" + soc);
  18. } catch (IOException ioe) {
  19. System.out.println("Server failed to accept");
  20. System.exit(1);
  21. }
  22. DataOutputStream dos = new DataOutputStream(soc.getOutputStream());
  23. BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
  24. String s;
  25. System.out.println("Server waiting for message from tthe client");
  26. boolean quit = false;
  27. do {
  28. String msg = "";
  29. s = br.readLine();
  30. int len = s.length();
  31. if (s.equals("exit")) {
  32. quit = true;
  33. }
  34. for (int i = 0; i < len; i++) {
  35. msg = msg + s.charAt(i);
  36. dos.write((byte) s.charAt(i));
  37. }
  38.  
  39. System.out.println("From client :" + msg);
  40. dos.write(13);
  41. dos.write(10);
  42. dos.flush();
  43. } while (!quit);
  44. dos.close();
  45. soc.close();
  46.  
  47. }
  48. }