Source Code Cross Referenced for ChatRoom.java in  » Net » QuickServer » chatserver » client » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Net » QuickServer » chatserver.client 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


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:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.