import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ChatServer {
public static void start(int port){
try {
ServerSocket server = new ServerSocket(port);
List<Socket> clients = new ArrayList<Socket>();
System.out.println("聊天室创建成功,等待成员加入!");
Socket client = null;
while(true){
client = server.accept();
clients.add(client); //加入客户端列表
//创建一个监听线程,接受客户端的消息并转发
new ServerListener(client, clients).start();
System.out.println("聊天室在线人数:"+clients.size());
}
} catch (IOException e) {
System.out.println("聊天室服务创建失败!");
e.printStackTrace();
}
}
public static void main(String[] args) {
ChatServer.start(Integer.parseInt(args[0])); //启动聊天服务
}
}
class ServerListener extends Thread{
private Socket client;
private List<Socket> clients;
public ServerListener(Socket client, List<Socket> clients) {
this.client = client;
this.clients = clients;
}
@Override
public void run() {
BufferedReader br = null;
PrintWriter pw = null;
PrintWriter clientspw = null;
if(!client.isClosed()&&client.isConnected()){
try {
br = new BufferedReader(new InputStreamReader(client.getInputStream()));
pw = new PrintWriter(client.getOutputStream());
String welcome = "欢迎"+client.getInetAddress().getHostName()+"加入聊天室!";
System.out.println(welcome);
pw.println(welcome);
pw.flush();
while(true){
if(!client.isClosed()&&client.isConnected()){
String message = client.getInetAddress().getHostName() + " 说:" + br.readLine(); //读取用户发来的消息
System.out.println(message);
for(Socket s : clients){
if(!client.getInetAddress().getHostAddress().equals(s.getInetAddress().getHostAddress())){
clientspw = new PrintWriter(s.getOutputStream());
clientspw.println(message);
clientspw.flush();
}
}
}
else{
clients.remove(client);
}
}
} catch (IOException ie) {
System.out.println("用户"+client.getInetAddress().getHostName()+"退出聊天室!");
try{
for(Socket s : clients){
if(!client.getInetAddress().getHostAddress().equals(s.getInetAddress().getHostAddress())){
clientspw = new PrintWriter(s.getOutputStream());
clientspw.println("用户"+client.getInetAddress().getHostName()+"退出聊天室!");
clientspw.flush();
}
}
}catch(IOException e){
e.printStackTrace();
}
clients.remove(client);
} finally{
try {
if(br!=null) br.close();
if(pw!=null) pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
clients.remove(client);
}
}
}
- 1
- 2
- 3
- 4
- 5
前往页