Java 实例 - Socket 实现多线程服务器程序

以下实例演示了如何使用 Socket 类的 accept() 方法和 ServerSocket 类的 MultiThreadServer(socketname) 方法来实现多线程服务器程序:

Main.java 文件

  1. import java.io.IOException;
  2. import java.io.PrintStream;
  3. import java.net.ServerSocket;
  4. import java.net.Socket;
  5. public class MultiThreadServer implements Runnable {
  6. Socket csocket;
  7. MultiThreadServer(Socket csocket) {
  8. this.csocket = csocket;
  9. }
  10. public static void main(String args[])
  11. throws Exception {
  12. ServerSocket ssock = new ServerSocket(1234);
  13. System.out.println("Listening");
  14. while (true) {
  15. Socket sock = ssock.accept();
  16. System.out.println("Connected");
  17. new Thread(new MultiThreadServer(sock)).start();
  18. }
  19. }
  20. public void run() {
  21. try {
  22. PrintStream pstream = new PrintStream
  23. (csocket.getOutputStream());
  24. for (int i = 100; i >= 0; i--) {
  25. pstream.println(i +
  26. " bottles of beer on the wall");
  27. }
  28. pstream.close();
  29. csocket.close();
  30. }
  31. catch (IOException e) {
  32. System.out.println(e);
  33. }
  34. }
  35. }

以上代码运行输出结果为:

  1. Listening
  2. Connected