package qq;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import static java.lang.System.out;
public class QQServer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// 从main参数取得server端口号
String port = args[0];
ServerSocket ss = new ServerSocket(Integer.parseInt(port));
out.println("QQ server is started...");
ArrayList<PrintWriter> printList = new ArrayList<PrintWriter>();
try {
while (true) {
// 阻塞,等待一个新的客户端连接
Socket socket = ss.accept();
// 为每个连接启动一个线程
new Service(socket, printList);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
ss.close();
}
}
}
class Service extends Thread {
private Socket socket;
private ArrayList<PrintWriter> poutList;
public Service(Socket socket, ArrayList<PrintWriter> poutList) {
this.socket = socket;
this.poutList = poutList;
this.start();
}
public void run() {
out.println("Client [" + socket.getPort() + "] is connected...");
PrintWriter pout = null;
try {
// 获得本连接输出流。为了多行输入,将自动flush设为false
pout = new PrintWriter(new OutputStreamWriter(socket
.getOutputStream()), false);
// 向新连接打印欢迎信息
welcome(pout);
// 将本连接输出流放入集合,用来向所有客户端发送消息
this.poutList.add(pout);
// 获得本连接输入流
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
while (true) {
// 阻塞
String str = in.readLine();
// 显示本客户端输入的消息
out.println("[" + socket.getPort() + "] says> " + str);
// 休眠100毫秒
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 如果客户端输入"end",则断开本连接
if ("end".equals(str))
break;
else {
// 向所有客户端打印本客户端文本
for (PrintWriter pwout : this.poutList) {
// 在server控制台显示向哪个客户端发送消息
out.println("To " + pwout);
pwout.println("[" + socket.getPort() + "] says> "
+ str);
pwout.flush();
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 从连接流集合中移除本客户端连接
if (pout != null)
this.poutList.remove(pout);
// 关闭socket
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
out.println("Connection " + socket.getPort() + " is closed...");
}
}
private static void welcome(PrintWriter pout) {
pout.println("***********************************************************");
pout.println("* *");
pout.println("* Welcome to talking room! *");
pout.println("* *");
pout.println("***********************************************************");
// 欢迎信息结束的约定
pout.println("wel_end");
pout.flush();
}
}