/**服务器
*/
package QQ;
import java.net.*;
import java.util.*;
import java.io.*;
public class QQServer {
/**
* @param args姜清华
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(9000);
Map map = new HashMap();
while (true) {
Socket s = ss.accept();
int len = 1;
Thread t = new ServerThread(s, len, map);
t.start();
}
}
}
class ServerThread extends Thread {
Socket s;
int len;
Map map;
public ServerThread(Socket s, int len, Map map) {
super();
this.s = s;
this.len = len;
this.map = map;
}
String s4 = null;
String s3 = null;
String[] string = new String[3];
public void run() {
try {
InputStream is = s.getInputStream();
InputStreamReader ir = new InputStreamReader(is);
BufferedReader in = new BufferedReader(ir);
while ((s3 = in.readLine()) != null) {
if (s3.indexOf(":name") != -1) {
StringTokenizer st = new StringTokenizer(s3, ":");
if (st.hasMoreTokens()) {
String str = st.nextToken();
s4 = str;
map.put(str, s);
Collection c=map.values();
Iterator it=c.iterator();
while(it.hasNext()){
Socket socket=(Socket )it.next();
OutputStream ops = socket.getOutputStream();
PrintWriter pw = new PrintWriter(ops);
Set set=map.keySet();
Iterator it1=set.iterator();
while(it1.hasNext()){
String s5=(String)it1.next();
pw.println(s5 + ":name");
pw.flush();
}
pw.println(s4+":welcome");
pw.flush();
}
}
/*
Set set = map.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Object o = it.next();
String s = (String) o;
Collection c = map.values();
Iterator it1 = c.iterator();
while (it1.hasNext()) {
Socket socket = (Socket) it1.next();
OutputStream ops = socket.getOutputStream();
PrintWriter pw = new PrintWriter(ops);
pw.println(s + ":name");
pw.flush();
}
}
*/
} else {
StringTokenizer st = new StringTokenizer(s3, ":");
int z = 0;
while (st.hasMoreTokens()) {
string[z] = st.nextToken();
z++;
}
Set set = map.keySet();
Iterator it = set.iterator();
int i = 0;
while (it.hasNext()) {
Object o = it.next();
String s = (String) o;
if (string[1].equals(s)) {
Socket s1 = (Socket) map.get(s);
OutputStream ops = s1.getOutputStream();
PrintWriter pw = new PrintWriter(ops);
pw.println(string[0] + string[2]);
pw.flush();
i = i + 1;
}
}
if (i == 0) {
Collection c = map.values();
Iterator it1 = c.iterator();
while (it1.hasNext()) {
Socket s = (Socket) it1.next();
OutputStream ops = s.getOutputStream();
PrintWriter pw = new PrintWriter(ops);
pw.println(s3);
pw.flush();
}
}
}
}
// 用户离开......................................
} catch (IOException e) {
//e.printStackTrace();
}finally{
String temp = s4;
map.remove(s4);
Collection c = map.values();
Iterator it1 = c.iterator();
try {
while (it1.hasNext()) {
Socket socket = (Socket) it1.next();
OutputStream ops = socket.getOutputStream();
PrintWriter pw = new PrintWriter(ops);
pw.println(temp + ":离开聊天室");
pw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}