Step 3 Implementation Information Sharing: One of the greatness of real-time communication networks on Socket is also information sharing, and Server can actively broadcast messages to all Client, while Client can also post messages to other clients. Let's take a look at how to develop a program that can deliver messages in real time.
Design principle:
The server is accepted by the client connection request, while starting a thread to handle this connection, the thread is constantly reading the client input, and then the input is added to the queue, waiting for processing. Add the thread to the queue while the thread is started to locate and take out when needed.
{Source code}
import java.io *;. import java.net *;. import java.util *;. import java.lang *;. public class Server extends ServerSocket {private static ArrayList User_List = new ArrayList (); private static ArrayList Threader = new ArrayList (); private static LinkedList Message_Array = new LinkedList (); private static int Thread_Counter = 0; private static boolean isClear = true; protected static final int SERVER_PORT = 10000; protected FileOutputStream LOG_FILE = new FileOutputStream ( "d: /connect.log ", true); public Server () throws FileNotFoundException, IOException {super (SERVER_PORT); new Broadcast (); // append connection logCalendar now = Calendar.getInstance (); String str =" [ " now.getTime (). TOSTRING () "] accepted a connection / 015/012"; byte [] TMP = str.getbytes (); log_file.write (TMP); try {while (TRUE) {socket socket = accept (); new createServertHread Socket);}} finally {close ();}} public static void main (string [] args) throws ooException {new server ();} // --- Broadcast () Broadcast Extends thread {public Broadcast () {star T ();} public void Run () {while {if (! isclear) {string tmp = (string) message_array.getfirst (); for (int i = 0; i
New PrintWriter (Client.getOutstream (), true); Out.println ("--- Welcome to this chat"); Out.println ("INPUT Your Nickname:"); start ();} public void sendMessage (String msg) {OUT.PRINTLN (MSG);} public void Run () {Try {INT flag = 0; Thread_Counter ; string line = in.readline (); while (! Line.equals ("bye")) { IF (Line.Equals ("L")) {out.println (ListonlineUsers ()); line = in.readline (); continue;} if (Flag == 0) {user_list.add (username) Out.println (ListonLineUsers (); threader.add (this); pushmessage ("[<" username "come on in in>]");} else {PushMessage ("<" username "> Line);} line = in.readline ();} out.println ("--- See you, bye! ---"); client.close ();} catch (ooException e) {} finally {TRY { CLIENT.CLOSE (); Catch (IOException E) {} thread_counter -; threader.remove (this); user_list.remove (username); PushMessage ("[<" username "left>]");}} Private string ListonlineUsers () {string s = "- - online list - - / 015/012"; for (int i = 0; i