分类: Java
2008-08-05 17:03:04
这是我自己写的一个C/S架构的类似MSN的聊天工具,当然功能和稳定性都差远了。下面就直入正题(由于篇幅过长,所以分两篇)
一、功能
多人在线绘图,即时显示,群聊,私聊,在线隐身转换,点歌,更改本地字体,剪切复制等很基本的功能,但都不是很完善。有兴趣的朋友可以看一下,对照这些功能可以再完善一下。
二、主要代码介绍
主要部分是ServerThread.java,ServerStartWindow.java,ClientThread.java,ClientFrame.其中ServerThread.java是服务器端用来处理多用户请求的一个线程,而ServerStartWindow.java负责连接这些线程。ClientThread.java是客户端的一个线程,负责接收服务器传来的信息,ClientFrame是客户端的界面,同时还肩负着向服务器发送信息的任务。下面我着重介绍一下这几个类。
ServerThread.java
先看一下构造函数
public ServerThread(Socket s, Vectorv) { this.socket = s; this.threads = v; try { oos = new ObjectOutputStream(socket.getOutputStream()); ois = new ObjectInputStream(socket.getInputStream()); new Thread(new Runnable() { public void run() { boolean first=true; while (true) { try { write(checkDatabase.getOnlineUser()); if(first){ Thread.sleep(1000); first=false; }else{ Thread.sleep(5000); } } catch (Exception e) { } } } }).start(); } catch (IOException e) { e.printStackTrace(); } }
这个构造函数并没什么特别,就是获得一个连接客户端的Socket,并且得到一个Vector
然后是这个线程类最重要的run方法
public void run() { Object o = this.read(); //从客户端读入对象 String flag = (String) o; //强转为String,flag是用来判断客户端这次操作主要目的是登录还是注册 if (flag.substring(0, 4).equals("name")) { //用户登录 sname = flag.substring(4); this.write(this.currentImage); System.out.println("have write currentImage"); //像这种System.out.println的都是调试程序用的 o = null; while (true) { o = this.read(); System.out.println("have read"); if (o == null) { System.out.println("read null"); } if (o instanceof String) { String msg = (String) o; if (msg.trim().equals("quit")) { checkDatabase.setUserOffline(sname); for (int i = 0; i < threads.size(); i++) { ServerThread st1 = threads.elementAt(i); st1.write("**********************" + sname + " leave ***********************\n"); st1.write(checkDatabase.getOnlineUser()); //write()方法是用来向客户端写入的 System.out.println("quit"); } threads.remove(this); //从线程向量中移除这个线程 break; } else if (msg.equals("iwanthide")) { //用户想隐身 checkDatabase.setUserOffline(sname); for (int i = 0; i < threads.size(); i++) { ServerThread st1 = threads.elementAt(i); st1.write(checkDatabase.getOnlineUser()); } } else if (msg.equals("iwantshow")) { checkDatabase.setUserOnline(sname); } else if (msg.equals("iwantcheck")) { //用户想要检索数据库的数据 System.out.println("have receiver check message...."); String[] checkMess = {"checkmessage", checkDatabase.getMessage(this.getName())}; this.write(checkMess); System.out.println("hafve writer check mess"); } else if (msg.length() >= 7) { if (msg.substring(0, 7).equals("private")) { String requestName = msg.substring(7); for (int k = 0; k < threads.size(); k++) { ServerThread str = threads.elementAt(k); if (str.getName().equals(requestName)) { String[] sRe = {"request", this.getName()}; str.write(sRe); break; } } }else if(msg.substring(0,9).equals("sendMusic")){ String musicName=msg.substring(9,14); System.out.println(musicName); String sendName=msg.substring(14); String[] music={"sendMusic",musicName}; for(int i=0;i