Java Socket线程的设计原理介绍

转自:http://developer.51cto.com/art/201003/190001.htm

Java Socket线程我们经常会用到的技术,但是有很多程序员还是有不少的使用问题,下面我们就看看如何才能进行有关的代码编写,希望大家又说收获。网络的伟大之一也是信息共享,Server可以主动向所有Client广播消息,同时Client也可以向其它Client发布消息。

下面看看如何开发一个可以实时传递消息的程序。

  1 import java.io.*;   
  2 import java.net.*;   
  3 import java.util.*;   
  4 import java.lang.*;   
  5 public class Server extends ServerSocket   
  6 {   
  7 private static ArrayList User_List = new ArrayList();   
  8 private static ArrayList Threader = new ArrayList();   
  9 private static LinkedList Message_Array = new LinkedList();   
 10 private static int Thread_Counter = 0;   
 11 private static boolean isClear = true;   
 12 protected static final int SERVER_PORT = 10000;   
 13 protected FileOutputStream LOG_FILE = new FileOutputStream("d:/connect.log", true);   
 14 public Server() throws FileNotFoundException, IOException   
 15 {   
 16 super(SERVER_PORT);   
 17 new Broadcast();   
 18 //append connection log   
 19 Calendar now = Calendar.getInstance();   
 20 String str = "[" + now.getTime().toString() + "] Accepted a connection1512";   
 21 byte[] tmp = str.getBytes();   
 22 LOG_FILE.write(tmp);   
 23 try   
 24 {   
 25 while (true)   
 26 {   
 27 Socket socket = accept();   
 28 new CreateServerThread(socket);   
 29 }   
 30 }   
 31 finally   
 32 {   
 33 close();   
 34 }   
 35 }   
 36 public static void main(String[] args) throws IOException   
 37 {   
 38 new Server();   
 39 }   
 40 //--- Broadcast   
 41 class Broadcast extends Thread   
 42 {   
 43 public Broadcast()   
 44 {   
 45 start();   
 46 }   
 47 public void run()   
 48 {   
 49 while (true)   
 50 {   
 51 if (!isClear)   
 52 {   
 53 String tmp = (String)Message_Array.getFirst();   
 54 for (int i = 0; i < Threader.size(); i++)   
 55 {   
 56 CreateServerThread client = (CreateServerThread)Threader.get(i);   
 57 client.sendMessage(tmp);   
 58 }  
 59 Message_Array.removeFirst();   
 60 isClear = Message_Array.size() > 0 ? false : true;   
 61 }   
 62 }   
 63 }   
 64 }   
 65 //--- CreateServerThread   
 66 class CreateServerThread extends Thread   
 67 {   
 68 private Socket client;   
 69 private BufferedReader in;   
 70 private PrintWriter out;   
 71 private String Username;   
 72 public CreateServerThread(Socket s) throws IOException   
 73 {   
 74 client = s;   
 75 in = new BufferedReader(new InputStreamReader(client.getInputStream()));   
 76 out = new PrintWriter(client.getOutputStream(), true);   
 77 out.println("--- Welcome to this chatroom ---");   
 78 out.println("Input your nickname:");   
 79 start();   
 80 }   
 81 public void sendMessage(String msg)   
 82 {   
 83 out.println(msg);   
 84 }   
 85 public void run()   
 86 {   
 87 try   
 88 {   
 89 int flag = 0;   
 90 Thread_Counter++;   
 91 String line = in.readLine();   
 92 while (!line.equals("bye"))   
 93 {   
 94 if (line.equals("l"))   
 95 {   
 96 out.println(listOnlineUsers());   
 97 line = in.readLine();   
 98 continue;   
 99 }   
100 if (flag++ == 0)   
101 {   
102 Username = line;   
103 User_List.add(Username);   
104 out.println(listOnlineUsers());   
105 Threader.add(this);   
106 pushMessage("[< " + Username + " come on in >]");   
107 }   
108 else   
109 {   
110 pushMessage("<" + Username + ">" + line);   
111 }   
112 line = in.readLine();   
113 }   
114 out.println("--- See you, bye! ---");   
115 client.close();   
116 }   
117 catch (IOException e)   
118 {}   
119 finally   
120 {   
121 try   
122 {  
123 client.close();   
124 }   
125 catch (IOException e)   
126 {}   
127 Thread_Counter--;   
128 Threader.remove(this);   
129 User_List.remove(Username);   
130 pushMessage("[< " + Username + " left>]");   
131 }   
132 }   
133 private String listOnlineUsers()   
134 {   
135 String s ="-+- Online list -+-1512";   
136 for (int i = 0; i < User_List.size(); i++)   
137 {   
138 s += "[" + User_List.get(i) + "]1512";   
139 }   
140 s += "-+---------------------+-";   
141 return s;   
142 }   
143 private void pushMessage(String msg)   
144 {   
145 Message_Array.addLast(msg);   
146 isClear = false;   
147 }   
148 }   
149 }  

以上就是对Java Socket线程的详细介绍。这就是程序运行后,多用户登陆并且输入信息后的屏幕。实现了信息的实时广播。用户输入"l"就可以列出在线人员表。

Java Socket线程的设计原理介绍

Java Socket线程如何才能更好的使用相关的技术应用呢?下面我们就看看如何才能更好的使用。希望大家有所收获。

作者:佚名来源:博客园|2010-03-19 17:47

Java Socket线程我们经常会用到的技术,但是有很多程序员还是有不少的使用问题,下面我们就看看如何才能进行有关的代码编写,希望大家又说收获。网络的伟大之一也是信息共享,Server可以主动向所有Client广播消息,同时Client也可以向其它Client发布消息。

下面看看如何开发一个可以实时传递消息的程序。

Java Socket线程的设计原理:

服务器端接受客户端的连接请求,同时启动一个线程处理这个连接,线程不停的读取客户端输入,然后把输入加入队列中,等候处理。在线程启动的同时将线程加入队列中,以便在需要的时候定位和取出。

{源码}

  1. import java.io.*;   
  2. import java.net.*;   
  3. import java.util.*;   
  4. import java.lang.*;   
  5. public class Server extends ServerSocket   
  6. {   
  7. private static ArrayList User_List = new ArrayList();   
  8. private static ArrayList Threader = new ArrayList();   
  9. private static LinkedList Message_Array = new LinkedList();   
  10. private static int Thread_Counter = 0;   
  11. private static boolean isClear = true;   
  12. protected static final int SERVER_PORT = 10000;   
  13. protected FileOutputStream LOG_FILE = new FileOutputStream("d:/connect.log", true);   
  14. public Server() throws FileNotFoundException, IOException   
  15. {   
  16. super(SERVER_PORT);   
  17. new Broadcast();   
  18. //append connection log   
  19. Calendar now = Calendar.getInstance();   
  20. String str = "[" + now.getTime().toString() + "] Accepted a connection1512";   
  21. byte[] tmp = str.getBytes();   
  22. LOG_FILE.write(tmp);   
  23. try   
  24. {   
  25. while (true)   
  26. {   
  27. Socket socket = accept();   
  28. new CreateServerThread(socket);   
  29. }   
  30. }   
  31. finally   
  32. {   
  33. close();   
  34. }   
  35. }   
  36. public static void main(String[] args) throws IOException   
  37. {   
  38. new Server();   
  39. }   
  40. //--- Broadcast   
  41. class Broadcast extends Thread   
  42. {   
  43. public Broadcast()   
  44. {   
  45. start();   
  46. }   
  47. public void run()   
  48. {   
  49. while (true)   
  50. {   
  51. if (!isClear)   
  52. {   
  53. String tmp = (String)Message_Array.getFirst();   
  54. for (int i = 0; i < Threader.size(); i++)   
  55. {   
  56. CreateServerThread client = (CreateServerThread)Threader.get(i);   
  57. client.sendMessage(tmp);   
  58. }  
  59. Message_Array.removeFirst();   
  60. isClear = Message_Array.size() > 0 ? false : true;   
  61. }   
  62. }   
  63. }   
  64. }   
  65. //--- CreateServerThread   
  66. class CreateServerThread extends Thread   
  67. {   
  68. private Socket client;   
  69. private BufferedReader in;   
  70. private PrintWriter out;   
  71. private String Username;   
  72. public CreateServerThread(Socket s) throws IOException   
  73. {   
  74. client = s;   
  75. in = new BufferedReader(new InputStreamReader(client.getInputStream()));   
  76. out = new PrintWriter(client.getOutputStream(), true);   
  77. out.println("--- Welcome to this chatroom ---");   
  78. out.println("Input your nickname:");   
  79. start();   
  80. }   
  81. public void sendMessage(String msg)   
  82. {   
  83. out.println(msg);   
  84. }   
  85. public void run()   
  86. {   
  87. try   
  88. {   
  89. int flag = 0;   
  90. Thread_Counter++;   
  91. String line = in.readLine();   
  92. while (!line.equals("bye"))   
  93. {   
  94. if (line.equals("l"))   
  95. {   
  96. out.println(listOnlineUsers());   
  97. line = in.readLine();   
  98. continue;   
  99. }   
  100. if (flag++ == 0)   
  101. {   
  102. Username = line;   
  103. User_List.add(Username);   
  104. out.println(listOnlineUsers());   
  105. Threader.add(this);   
  106. pushMessage("[< " + Username + " come on in >]");   
  107. }   
  108. else   
  109. {   
  110. pushMessage("<" + Username + ">" + line);   
  111. }   
  112. line = in.readLine();   
  113. }   
  114. out.println("--- See you, bye! ---");   
  115. client.close();   
  116. }   
  117. catch (IOException e)   
  118. {}   
  119. finally   
  120. {   
  121. try   
  122. {  
  123. client.close();   
  124. }   
  125. catch (IOException e)   
  126. {}   
  127. Thread_Counter--;   
  128. Threader.remove(this);   
  129. User_List.remove(Username);   
  130. pushMessage("[< " + Username + " left>]");   
  131. }   
  132. }   
  133. private String listOnlineUsers()   
  134. {   
  135. String s ="-+- Online list -+-1512";   
  136. for (int i = 0; i < User_List.size(); i++)   
  137. {   
  138. s += "[" + User_List.get(i) + "]1512";   
  139. }   
  140. s += "-+---------------------+-";   
  141. return s;   
  142. }   
  143. private void pushMessage(String msg)   
  144. {   
  145. Message_Array.addLast(msg);   
  146. isClear = false;   
  147. }   
  148. }   
  149. }  

以上就是对Java Socket线程的详细介绍。这就是程序运行后,多用户登陆并且输入信息后的屏幕。实现了信息的实时广播。用户输入"l"就可以列出在线人员表。

原文地址:https://www.cnblogs.com/sharpest/p/10054584.html