AppServer.java 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.*;
  4. /**
  5. * 聊天服务器
  6. */
  7. public class AppServer extends Thread {
  8. private ServerSocket serverSocket;
  9. private ServerFrame sFrame;
  10. private static Vector userOnline = new Vector(1, 1);
  11. private static Vector v = new Vector(1, 1);
  12. /**
  13. * 创建服务器 启动服务监听1001端口
  14. */
  15. public AppServer() {
  16. sFrame = new ServerFrame();
  17. try {
  18. serverSocket = new ServerSocket(1001);
  19. InetAddress address = InetAddress.getLocalHost();
  20. sFrame.txtServerName.setText(address.getHostName());
  21. sFrame.txtIP.setText(address.getHostAddress());
  22. sFrame.txtPort.setText("1001");
  23. } catch (IOException e) {
  24. fail(e, "不能启动服务!");
  25. }
  26. sFrame.txtStatus.setText("已启动...");
  27. this.start(); // 启动线程
  28. }
  29. // 退出服务器
  30. public static void fail(Exception e, String str) {
  31. System.out.println(str + " 。" + e);
  32. }
  33. /**
  34. * 监听客户的请求,当有用户请求时创建 Connection线程
  35. */
  36. public void run() {
  37. try {
  38. while (true) {
  39. Socket client = serverSocket.accept();
  40. new Connection(sFrame, client, userOnline, v); // 支持多线程
  41. }
  42. } catch (IOException e) {
  43. fail(e, "不能监听!");
  44. }
  45. }
  46. /**
  47. * 启动服务器
  48. */
  49. public static void main(String args[]) {
  50. new AppServer();
  51. }
  52. }