001: /*
002: * This file is part of the QuickServer library
003: * Copyright (C) 2003-2005 QuickServer.org
004: *
005: * Use, modification, copying and distribution of this software is subject to
006: * the terms and conditions of the GNU Lesser General Public License.
007: * You should have received a copy of the GNU LGP License along with this
008: * library; if not, you can download a copy from <http://www.quickserver.org/>.
009: *
010: * For questions, suggestions, bug-reports, enhancement-requests etc.
011: * visit http://www.quickserver.org
012: *
013: */
014:
015: package chatserver.client;
016:
017: import java.net.*;
018: import java.io.*;
019: import java.util.logging.*;
020: import java.util.*;
021:
022: /**
023: *
024: * @author Akshathkumar Shetty
025: */
026: public class ChatRoom {
027: private static Logger logger = Logger.getLogger(ChatRoom.class
028: .getName());
029:
030: private Socket socket;
031: private InputStream in;
032: private OutputStream out;
033: private BufferedReader br;
034: private BufferedWriter bw;
035: private String room = "home";
036:
037: private volatile boolean connected = false;
038: private volatile boolean loggedIn = false;
039:
040: //gui
041: ChatWindow chatWindow = null;
042:
043: private LinkedList receivedMsg;
044:
045: /** Creates a new instance of ChatRoom */
046: public ChatRoom() {
047: this (null);
048: }
049:
050: // args: room host_ip port
051: // defaults: home 127.0.0.1 7412
052: public ChatRoom(String args[]) {
053: Logger _logger = Logger.getLogger("");
054: _logger.setLevel(Level.FINEST);
055:
056: _logger = Logger.getLogger("chatserver.client");
057: _logger.setLevel(Level.FINEST);
058:
059: if (args != null && args.length >= 1)
060: setRoom(args[0]);
061: chatWindow = new ChatWindow(this , args);
062: chatWindow.setVisible(true);
063: }
064:
065: public String getRoom() {
066: return room;
067: }
068:
069: public void setRoom(String room) {
070: this .room = room;
071: }
072:
073: /**
074: * ChatRoom room ip port
075: * @param args the command line arguments
076: */
077: public static void main(final String[] args) {
078: Logger logger = Logger.getLogger("chatserver.client");
079: logger.setLevel(Level.FINEST);
080: /*
081: try {
082: javax.swing.UIManager.setLookAndFeel(
083: javax.swing.UIManager.getSystemLookAndFeelClassName());
084: } catch(Exception ee) {}
085: */
086: java.awt.EventQueue.invokeLater(new Runnable() {
087: public void run() {
088: if (args.length != 0)
089: new ChatRoom(args);
090: else
091: new ChatRoom();
092: }
093: });
094: }
095:
096: public void changeRoom(String newRoom) {
097: if (socket == null)
098: chatWindow.setResponse("-ERR Not connected");
099: try {
100: sendCommand("changeRoom " + newRoom, true);
101: } catch (Exception e) {
102: chatWindow.setResponse("-ERR Error: " + e.getMessage());
103: }
104: setRoom(newRoom);
105: }
106:
107: public void updateUserList() {
108: sendCommand("userList", true);
109: }
110:
111: public void doLogout() throws IOException {
112: if (socket == null)
113: throw new IllegalStateException("Not connected");
114: sendCommand("quit", true);
115: connected = false;
116: clean();
117: }
118:
119: public boolean doLogin(String ipAddress, int port, String username,
120: String password) throws IOException {
121: connected = false;
122: loggedIn = false;
123: chatWindow.log("Logging in to " + ipAddress + ":" + port);
124: try {
125: socket = new Socket(ipAddress, port);
126: connected = true;
127: in = socket.getInputStream();
128: out = socket.getOutputStream();
129: br = new BufferedReader(new InputStreamReader(in));
130: bw = new BufferedWriter(new OutputStreamWriter(out));
131: startSocketListener();
132:
133: String res = null;
134:
135: res = sendCommunicationSilent(null, true);
136: if (res.startsWith("{system.msg} ") == false)
137: throw new IOException(res.substring(13));
138:
139: for (int i = 0; i < 2; i++) {
140: res = sendCommunicationSilent(null, true);
141: if (res.startsWith("{system.help} ") == false)
142: throw new IOException(res.substring(14));
143: }
144:
145: res = sendCommunicationSilent(null, true);
146: if (res.startsWith("{system.data} ") == false)
147: throw new IOException(res.substring(13));
148: //gui.setResponse(res);
149:
150: //try to login
151: res = sendCommunicationSilent(username, true);
152:
153: //password
154: /*
155: StringBuffer buffer = new StringBuffer();
156: for(int i=0;i<password.length();i++)
157: buffer.append('*');
158: getGUI().appendToConsole(buffer.toString());
159: */
160: res = sendCommunicationSilent(password, false);
161: res = sendCommunicationSilent(room, true);
162:
163: if (res.startsWith("{system.ok} ")) {
164: chatWindow.log("Authorised");
165: chatWindow.setTitle("QuickChat - Room: " + room + "@"
166: + ipAddress + ":" + port + " Logged as "
167: + username);
168: loggedIn = true;
169: updateUserList();
170: } else {
171: loggedIn = false;
172: //{system.error}
173: chatWindow.log("Error : " + res);
174: throw new IOException(res.substring(15));
175: }
176: return true;
177: } catch (UnknownHostException e) {
178: if (socket != null)
179: socket.close();
180: chatWindow.log("Error " + e);
181: connected = false;
182: loggedIn = false;
183: socket = null;
184: in = null;
185: out = null;
186: br = null;
187: bw = null;
188: chatWindow.setResponse("-ERR Unknown Host : "
189: + e.getMessage());
190: return false;
191: } catch (Exception e) {
192: if (socket != null)
193: socket.close();
194: chatWindow.log("Error " + e);
195: connected = false;
196: socket = null;
197: in = null;
198: out = null;
199: br = null;
200: bw = null;
201: chatWindow.setResponse("-ERR " + e.getMessage());
202: return false;
203: }
204: }
205:
206: public void startSocketListener() {
207: receivedMsg = new LinkedList();
208: Thread t = new Thread() {
209: public void run() {
210: String rec = null;
211: chatWindow.log("Started: startSocketListener");
212: while (true) {
213: try {
214: rec = br.readLine();
215: } catch (IOException e) {
216: logger.warning("Error : " + e);
217: if (isConnected() == true && loggedIn == true) {
218: chatWindow.log("Error : " + e);
219: chatWindow.addChatMessage("{system.error} "
220: + e.getMessage());
221: clean();
222: }
223: break;
224: }
225: if (rec == null) {
226: if (isConnected() == true) {
227: chatWindow.log("Lost Connection!");
228: chatWindow
229: .addChatMessage("{system.error} Lost Connection!");
230: clean();
231: }
232: break;
233: }
234: receivedMsg.add(rec);
235: chatWindow.log("R: " + rec);
236: if (loggedIn == true) {
237: receivedMsg.remove(rec);
238: if (rec.startsWith("{user.list} "))
239: chatWindow.addToUserList(rec.substring(12));
240: else
241: chatWindow.addChatMessage(rec);
242: }
243: }
244: chatWindow.log("Finished: startSocketListener");
245: }
246: };
247: t.setPriority(Thread.NORM_PRIORITY);
248: t.start();
249: }
250:
251: public void sendCommand(String command, boolean echo) {
252: logger.fine("Got command : " + command);
253: if (isConnected() == false) {
254: chatWindow.setResponse("-ERR Not connected yet.");
255: return;
256: }
257: if (command != null && command.equals("") == false) {
258: if (socket == null)
259: throw new IllegalStateException("Not connected");
260: if (echo == true)
261: chatWindow.log("S: " + command);
262: command += "\r\n";
263: try {
264: bw.write(command, 0, command.length());
265: bw.flush();
266: } catch (Exception e) {
267: chatWindow.setResponse("-ERR " + e.getMessage());
268: }
269: }
270: }
271:
272: public synchronized String sendCommunicationSilent(String command,
273: boolean echo) throws IOException {
274: if (isConnected() == false)
275: return "-ERR Not connected yet";
276: if (socket == null)
277: throw new IllegalStateException("Not connected");
278: if (command != null && command.equals("") == false) {
279: logger.fine("Got command : " + command);
280: if (echo == true)
281: chatWindow.log("S: " + command);
282: command += "\r\n";
283: emptyReceivedMsg();
284: bw.write(command, 0, command.length());
285: bw.flush();
286: }
287: return readResponse();
288: }
289:
290: public String getReceivedMsg() {
291: while (receivedMsg.size() == 0 && isConnected() == true) {
292: try {
293: Thread.currentThread().sleep(50);
294: } catch (InterruptedException e) {
295: logger.warning("Error : " + e);
296: }
297: }
298: if (receivedMsg.size() != 0)
299: return (String) receivedMsg.removeFirst();
300: else
301: return null;
302: }
303:
304: public void emptyReceivedMsg() {
305: receivedMsg.clear();
306: }
307:
308: public void processReceivedMsg() {
309: while (receivedMsg.size() != 0) {
310: chatWindow.addChatMessage((String) receivedMsg
311: .removeFirst());
312: }
313: }
314:
315: public String readResponse() {
316: return getReceivedMsg();
317: }
318:
319: public boolean isConnected() {
320: return connected;
321: }
322:
323: private void clean() {
324: if (socket != null) {
325: try {
326: socket.close();
327: } catch (Exception e) {
328: logger.warning("Error : " + e);
329: }
330: socket = null;
331: }
332: in = null;
333: out = null;
334: br = null;
335: bw = null;
336: connected = false;
337: processReceivedMsg();
338: loggedIn = false;
339: chatWindow.enableChat(false);
340: }
341:
342: public void sendMessage(String msg) {
343: sendCommand("sendMsgToRoom " + room + " " + msg, true);
344: }
345:
346: public void sendPrivateMessage(String userid, String msg) {
347: if (userid == null)
348: return;
349: chatWindow.addChatMessage("{msg.user:" + userid + "} " + msg);
350: sendCommand("sendMsg " + userid + " " + msg, true);
351: }
352:
353: }
|