KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sellwin > server > ChatHandler


1 package sellwin.server;
2
3 import java.io.*;
4 import java.net.*;
5 import java.util.*;
6 import sellwin.domain.*;
7
8 // SellWin http://sourceforge.net/projects/sellwincrm
9
//Contact support@open-app.com for commercial help with SellWin
10
//This software is provided "AS IS", without a warranty of any kind.
11

12
13 /**
14  * this class handles chat client connections, basically
15  * implements the simple chat protocol (LOGON, QUERY, SEND)
16  */

17 public class ChatHandler extends Thread JavaDoc {
18
19     private static Vector handlers = new Vector( 10 );
20     private Socket socket;
21     private ObjectInputStream ois=null;
22     private ObjectOutputStream oos=null;
23     private PrintWriter out;
24     private TreeMap onlineUsers = null;
25
26     /**
27      * construct a handler for a client's socket
28      * @param socket the client's socket we read-write from-to
29      * @param onlineUsers the global list of online users
30      */

31     public ChatHandler(Socket socket, TreeMap onlineUsers) throws IOException {
32
33         this.onlineUsers = onlineUsers;
34         this.socket = socket;
35         ois = new ObjectInputStream(socket.getInputStream());
36         oos = new ObjectOutputStream(socket.getOutputStream());
37     }
38
39     /**
40      * this handler is a Thread, so this is the Thread's run() method
41      * that gets executed upon a start()
42      * handles the chat packets read from the various chat clients
43      *
44      */

45     public void run() {
46
47         String JavaDoc line;
48
49         synchronized(handlers) {
50             handlers.addElement(this);
51         }
52
53         try {
54             while(true) {
55
56                 ChatPacket msg = (ChatPacket)ois.readObject();
57
58                 switch (msg.getAction()) {
59
60                 case ChatPacket.QUERY_USERS:
61                     queryRequest(msg);
62                     break;
63
64                 case ChatPacket.LOGON:
65                     logonRequest( oos, msg);
66                     break;
67     
68                 case ChatPacket.SEND_MSG:
69                     userCheck(msg);
70                     msg.print();
71                     sendReply(msg);
72                     break;
73                 default:
74                     System.out.println("outrageous error here");
75                     System.exit(-1);
76                 }
77
78                 for (int i = 0; i < handlers.size(); i++) {
79                     synchronized(handlers) {
80                         ChatHandler handler =
81                         (ChatHandler)handlers.elementAt(i);
82                     }
83                 }
84             }
85         } catch(ClassNotFoundException JavaDoc cl) {
86             cl.printStackTrace();
87         } catch(IOException ioe) {
88             ioe.printStackTrace();
89         } finally {
90             try {
91                 ois.close();
92                 oos.close();
93                 socket.close();
94             } catch(IOException ioe) {
95                 ioe.printStackTrace();
96             } finally {
97                 synchronized(handlers) {
98                     handlers.removeElement(this);
99                 }
100             }
101         }
102     }
103
104     /**
105      * check to see if the chat client user is in the online user
106      * list, if not, add them
107      * @param msg the online Chat user's message just received
108      */

109     private void userCheck(ChatPacket msg) {
110
111         if (onlineUsers.containsKey(msg.getSender()))
112             System.out.println(msg.getSender() + " already in online list");
113         else {
114             ChatConnInfo info = new ChatConnInfo(msg.getSender(), oos, new java.util.Date JavaDoc());
115             System.out.println("adding " + msg.getSender() + " at " + info.getConnectedSince());
116             onlineUsers.put(msg.getSender(), info);
117         }
118     }
119
120     /**
121      * handle the chat client's logon request
122      * @param oos the client's output stream to reply to
123      * @param msg the logon request packet received
124      */

125     private void logonRequest(ObjectOutputStream oos, ChatPacket msg) {
126         System.out.println("logon request...");
127         ChatConnInfo info = new ChatConnInfo(msg.getSender(), oos, new java.util.Date JavaDoc());
128         onlineUsers.put(msg.getSender(), info);
129     }
130
131     /**
132      * send a reply to the clients specified in the SEND request
133      * @param msg the client's packet we received
134      */

135     private void sendReply(ChatPacket msg) {
136
137         ArrayList toUsers = msg.getToList();
138         String JavaDoc toUser=null;
139         ObjectOutputStream userOOS = null;
140
141         for (int i=0; i<toUsers.size(); i++) {
142             toUser = (String JavaDoc)toUsers.get(i);
143             System.out.println("sending reply to " + toUser);
144             userOOS = lookupUserOutputStream(toUser);
145
146             try {
147                 if (userOOS != null) {
148                     System.out.println("actually wrote back a reply");
149                     userOOS.writeObject(msg);
150                 }
151             } catch (IOException e) {
152                 e.printStackTrace();
153             }
154         }
155     }
156
157     /**
158      * find a recipient's output stream so we can send them a
159      * message
160      * @param toUser the key or user ID we index into the global
161      * list of online users
162      * @return the user's output stream
163      */

164     private ObjectOutputStream lookupUserOutputStream(String JavaDoc toUser) {
165
166         ChatConnInfo connInfo = (ChatConnInfo)onlineUsers.get(toUser);
167         if ((connInfo != null) && (connInfo.stillConnected()))
168             return connInfo.getOOS();
169         else
170             return null;
171     }
172
173     /**
174      * handle a user's query request for the currently logged on
175      * list of users
176      * @param msg the user's query request message
177      */

178     private void queryRequest(ChatPacket msg) {
179         System.out.println("query request...");
180
181         //update the user's timestamp to mark them as 'online'..accomplishes
182
//the heartbeat of the protocol
183

184         ChatConnInfo info = new ChatConnInfo(msg.getSender(), oos, new java.util.Date JavaDoc());
185         System.out.println("msg.getSender = " + msg.getSender());
186         System.out.println("info.getSender=" + info.getSender());
187         onlineUsers.put(msg.getSender(), info);
188
189         //get the list of online users
190

191         Set keys = onlineUsers.keySet();
192         Object JavaDoc[] keysArray = keys.toArray();
193         ArrayList tempList = new ArrayList();
194         for (int i=0;i<onlineUsers.size();i++) {
195             info = (ChatConnInfo)onlineUsers.get(keysArray[i]);
196             System.out.println((String JavaDoc)keysArray[i] + "-" + info.getSender());
197             tempList.add(keysArray[i]);
198         }
199
200         //send back the ArrayList of online users
201

202         msg = new ChatPacket();
203         msg.setSender("server");
204         msg.setOnlineUsers(tempList);
205         msg.setAction(ChatPacket.QUERY_USERS);
206         try {
207             oos.writeObject(msg);
208         } catch (IOException e) {
209             e.printStackTrace();
210         }
211     }
212 }
213
Popular Tags