文件名称:java聊天室源程序
文件大小:8KB
文件格式:TXT
更新时间:2014-05-31 15:03:48
java聊天室
最近两周闲的无聊,课题也不想做了,就写了一个聊天室程序,放在实验室让大家玩玩,代码如下,分为客户端和服务器端。希望大家多给点意见 服务器端: 1 BroadCast.java package server; import java.io.*; public class BroadCast extends Thread { ClientThread clientthread; ServerThread serverthread; String str; public BroadCast(ServerThread serverthread) { this.serverthread = serverthread; } public void run() { while(true) { try { Thread.sleep(300); } catch(InterruptedException e) { e.printStackTrace(); } //当有用户登陆聊天室的时候先广播名字 synchronized (serverthread.clients) { for(int i = 0;i < serverthread.clients.size();i++) { clientthread = (ClientThread)serverthread.clients.elementAt(i); try { for(int j = 0;j < serverthread.name.size();j++) { clientthread.out.writeUTF((String)this.serverthread.name.elementAt(j)); } } catch(IOException e) { e.printStackTrace(); } } } synchronized (serverthread.messages) { if(serverthread.messages.isEmpty()) { continue; } str = (String)this.serverthread.messages.firstElement(); this.serverthread.messages.removeElement(str); } synchronized (serverthread.clients) { for(int i = 0;i < serverthread.clients.size();i++) { clientthread = (ClientThread)serverthread.clients.elementAt(i); try { //先将所有用户的名字传播出去 /** for(int j = 0;j < serverthread.name.size();j++) { clientthread.out.writeUTF((String)this.serverthread.name.elementAt(j)); }**/ clientthread.out.writeUTF(str); } catch(IOException e) { e.printStackTrace(); } } } } } }