KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > chatserver > client > ChatRoom


1 /*
2  * This file is part of the QuickServer library
3  * Copyright (C) 2003-2005 QuickServer.org
4  *
5  * Use, modification, copying and distribution of this software is subject to
6  * the terms and conditions of the GNU Lesser General Public License.
7  * You should have received a copy of the GNU LGP License along with this
8  * library; if not, you can download a copy from <http://www.quickserver.org/>.
9  *
10  * For questions, suggestions, bug-reports, enhancement-requests etc.
11  * visit http://www.quickserver.org
12  *
13  */

14
15 package chatserver.client;
16
17 import java.net.*;
18 import java.io.*;
19 import java.util.logging.*;
20 import java.util.*;
21
22 /**
23  *
24  * @author Akshathkumar Shetty
25  */

26 public class ChatRoom {
27     private static Logger logger = Logger.getLogger(ChatRoom.class.getName());
28     
29     private Socket socket;
30     private InputStream in;
31     private OutputStream out;
32     private BufferedReader br;
33     private BufferedWriter bw;
34     private String JavaDoc room = "home";
35     
36     private volatile boolean connected = false;
37     private volatile boolean loggedIn = false;
38     
39     //gui
40
ChatWindow chatWindow = null;
41     
42     private LinkedList receivedMsg;
43     
44     /** Creates a new instance of ChatRoom */
45     public ChatRoom() {
46         this(null);
47     }
48
49     // args: room host_ip port
50
// defaults: home 127.0.0.1 7412
51
public ChatRoom(String JavaDoc args[]) {
52         Logger _logger = Logger.getLogger("");
53         _logger.setLevel(Level.FINEST);
54         
55         _logger = Logger.getLogger("chatserver.client");
56         _logger.setLevel(Level.FINEST);
57
58         if(args!=null && args.length>=1) setRoom(args[0]);
59         chatWindow = new ChatWindow(this, args);
60         chatWindow.setVisible(true);
61     }
62
63     public String JavaDoc getRoom() {
64         return room;
65     }
66     
67     public void setRoom(String JavaDoc room) {
68         this.room = room;
69     }
70     
71     /**
72      * ChatRoom room ip port
73      * @param args the command line arguments
74      */

75     public static void main(final String JavaDoc[] args) {
76         Logger logger = Logger.getLogger("chatserver.client");
77         logger.setLevel(Level.FINEST);
78         /*
79         try {
80             javax.swing.UIManager.setLookAndFeel(
81                 javax.swing.UIManager.getSystemLookAndFeelClassName());
82         } catch(Exception ee) {}
83         */

84         java.awt.EventQueue.invokeLater(new Runnable JavaDoc() {
85             public void run() {
86                 if(args.length!=0)
87                     new ChatRoom(args);
88                 else
89                     new ChatRoom();
90             }
91         });
92     }
93
94     public void changeRoom(String JavaDoc newRoom) {
95          if(socket==null) chatWindow.setResponse("-ERR Not connected");
96          try {
97              sendCommand("changeRoom "+newRoom, true);
98          } catch(Exception JavaDoc e) {
99              chatWindow.setResponse("-ERR Error: "+e.getMessage());
100          }
101          setRoom(newRoom);
102     }
103
104     public void updateUserList() {
105         sendCommand("userList", true);
106     }
107     
108     public void doLogout() throws IOException {
109         if(socket==null)
110             throw new IllegalStateException JavaDoc("Not connected");
111         sendCommand("quit", true);
112         connected = false;
113         clean();
114     }
115     
116     public boolean doLogin(String JavaDoc ipAddress, int port,
117             String JavaDoc username, String JavaDoc password) throws IOException {
118         connected = false;
119         loggedIn = false;
120         chatWindow.log("Logging in to " + ipAddress + ":"+port);
121         try {
122             socket = new Socket(ipAddress, port);
123             connected = true;
124             in = socket.getInputStream();
125             out = socket.getOutputStream();
126             br = new BufferedReader(new InputStreamReader(in));
127             bw = new BufferedWriter(new OutputStreamWriter(out));
128             startSocketListener();
129             
130             String JavaDoc res = null;
131             
132             res = sendCommunicationSilent(null, true);
133             if(res.startsWith("{system.msg} ")==false)
134                 throw new IOException(res.substring(13));
135             
136             for(int i=0;i<2;i++){
137                 res = sendCommunicationSilent(null, true);
138                 if(res.startsWith("{system.help} ")==false)
139                     throw new IOException(res.substring(14));
140             }
141             
142             res = sendCommunicationSilent(null, true);
143             if(res.startsWith("{system.data} ")==false)
144                 throw new IOException(res.substring(13));
145             //gui.setResponse(res);
146

147             //try to login
148
res = sendCommunicationSilent(username, true);
149             
150             //password
151
/*
152             StringBuffer buffer = new StringBuffer();
153             for(int i=0;i<password.length();i++)
154                 buffer.append('*');
155             getGUI().appendToConsole(buffer.toString());
156              */

157             res = sendCommunicationSilent(password, false);
158             res = sendCommunicationSilent(room, true);
159             
160             if(res.startsWith("{system.ok} ")) {
161                 chatWindow.log("Authorised");
162                 chatWindow.setTitle("QuickChat - Room: "+room+"@"+
163                     ipAddress+":"+port+" Logged as "+username);
164                 loggedIn = true;
165                 updateUserList();
166             } else {
167                 loggedIn = false;
168                 //{system.error}
169
chatWindow.log("Error : "+res);
170                 throw new IOException(res.substring(15));
171             }
172             return true;
173         } catch(UnknownHostException e) {
174             if(socket!=null) socket.close();
175             chatWindow.log("Error "+e);
176             connected = false;
177             loggedIn = false;
178             socket = null;
179             in = null;
180             out = null;
181             br = null;
182             bw = null;
183             chatWindow.setResponse("-ERR Unknown Host : "+e.getMessage());
184             return false;
185         } catch(Exception JavaDoc e) {
186             if(socket!=null) socket.close();
187             chatWindow.log("Error "+e);
188             connected = false;
189             socket = null;
190             in = null;
191             out = null;
192             br = null;
193             bw = null;
194             chatWindow.setResponse("-ERR "+e.getMessage());
195             return false;
196         }
197     }
198     
199     public void startSocketListener() {
200         receivedMsg = new LinkedList();
201         Thread JavaDoc t = new Thread JavaDoc() {
202             public void run() {
203                 String JavaDoc rec = null;
204                 chatWindow.log("Started: startSocketListener");
205                 while(true) {
206                     try {
207                         rec = br.readLine();
208                     } catch(IOException e) {
209                         logger.warning("Error : "+e);
210                         if(isConnected()==true && loggedIn==true) {
211                             chatWindow.log("Error : "+e);
212                             chatWindow.addChatMessage("{system.error} "+e.getMessage());
213                             clean();
214                         }
215                         break;
216                     }
217                     if(rec==null) {
218                         if(isConnected()==true) {
219                             chatWindow.log("Lost Connection!");
220                             chatWindow.addChatMessage("{system.error} Lost Connection!");
221                             clean();
222                         }
223                         break;
224                     }
225                     receivedMsg.add(rec);
226                     chatWindow.log("R: "+rec);
227                     if(loggedIn==true) {
228                         receivedMsg.remove(rec);
229                         if(rec.startsWith("{user.list} "))
230                             chatWindow.addToUserList(rec.substring(12));
231                         else
232                             chatWindow.addChatMessage(rec);
233                     }
234                 }
235                chatWindow.log("Finished: startSocketListener");
236             }
237         };
238         t.setPriority(Thread.NORM_PRIORITY);
239         t.start();
240     }
241     
242     public void sendCommand(String JavaDoc command, boolean echo) {
243         logger.fine("Got command : "+command);
244         if(isConnected()==false) {
245             chatWindow.setResponse("-ERR Not connected yet.");
246             return;
247         }
248         if(command!=null && command.equals("")==false) {
249             if(socket==null)
250                 throw new IllegalStateException JavaDoc("Not connected");
251             if(echo==true)
252                 chatWindow.log("S: "+command);
253             command += "\r\n";
254             try {
255                 bw.write(command, 0, command.length());
256                 bw.flush();
257             } catch(Exception JavaDoc e) {
258                 chatWindow.setResponse("-ERR "+e.getMessage());
259             }
260         }
261     }
262     
263     public synchronized String JavaDoc sendCommunicationSilent(String JavaDoc command,
264             boolean echo) throws IOException {
265         if(isConnected()==false)
266             return "-ERR Not connected yet";
267         if(socket==null)
268             throw new IllegalStateException JavaDoc("Not connected");
269         if(command!=null && command.equals("")==false) {
270             logger.fine("Got command : "+command);
271             if(echo==true)
272                 chatWindow.log("S: "+command);
273             command += "\r\n";
274             emptyReceivedMsg();
275             bw.write(command, 0, command.length());
276             bw.flush();
277         }
278         return readResponse();
279     }
280     
281     public String JavaDoc getReceivedMsg() {
282         while(receivedMsg.size()==0 && isConnected()==true) {
283             try {
284                 Thread.currentThread().sleep(50);
285             } catch(InterruptedException JavaDoc e) {
286                 logger.warning("Error : "+e);
287             }
288         }
289         if(receivedMsg.size()!=0)
290             return (String JavaDoc)receivedMsg.removeFirst();
291         else
292             return null;
293     }
294     
295     public void emptyReceivedMsg() {
296         receivedMsg.clear();
297     }
298     
299     public void processReceivedMsg() {
300         while(receivedMsg.size()!=0) {
301             chatWindow.addChatMessage( (String JavaDoc)receivedMsg.removeFirst() );
302         }
303     }
304     
305     public String JavaDoc readResponse() {
306         return getReceivedMsg();
307     }
308     
309     public boolean isConnected(){
310         return connected;
311     }
312     
313     private void clean() {
314         if(socket!=null) {
315             try {
316                 socket.close();
317             } catch(Exception JavaDoc e) {
318                 logger.warning("Error : "+e);
319             }
320             socket = null;
321         }
322         in = null;
323         out = null;
324         br = null;
325         bw = null;
326         connected = false;
327         processReceivedMsg();
328         loggedIn = false;
329         chatWindow.enableChat(false);
330     }
331     
332     public void sendMessage(String JavaDoc msg) {
333         sendCommand("sendMsgToRoom "+room+" "+msg, true);
334     }
335     
336     public void sendPrivateMessage(String JavaDoc userid, String JavaDoc msg) {
337         if(userid==null) return;
338         chatWindow.addChatMessage("{msg.user:"+userid+"} "+msg);
339         sendCommand("sendMsg "+userid+" "+msg, true);
340     }
341
342 }
343
Popular Tags