server:
package com.socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
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 java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**1.服务器程序:
* com Server
*
* @author hechuan
* @version 1.0
*/
public class Main {
private static final int PORT = 9999;// 端口监听
private List<Socket> mList = new ArrayList<Socket>();// 存放客户端socket
private ServerSocket server = null;
private ExecutorService mExecutorService = null;// 线程池
/**
* @param args
*/
public static void main(String[] args) {
new Main();
}
public Main() {
try {
server = new ServerSocket(PORT);
mExecutorService = Executors.newCachedThreadPool();// 创建一个线程池
System.out.println("Server Start...");
Socket client = null;
while (true) {
client = server.accept();
mList.add(client);
mExecutorService.execute(new Service(client));// 开启一个客户端线程.
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public class Service implements Runnable {
private Socket socket;
private BufferedReader in = null;
private String msg = "";
public Service(Socket socket) {
this.socket = socket;
try {
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
msg = "user:" + this.socket.getInetAddress() + " time "+DateTime.getTimeLocal("s")+" come total:"
+ mList.size();
this.sendmsg();
} catch (IOException e) {
System.out.println(e.getLocalizedMessage());
}
}
public void run() {
try {
while (true) {
if ((msg = in.readLine()) != null) {
if (msg.equals("exit")) {
mList.remove(socket);
in.close();
msg = "user:" + socket.getInetAddress()
+ " exit total:" + mList.size();
socket.close();
this.sendmsg();
break;
} else {
msg = socket.getInetAddress() + " : " + new String(msg.getBytes(),"UTF-8");
this.sendmsg();
}
}
}
} catch (Exception ex) {
//add by hechuan begin
mList.remove(socket);
//add by hechuan end
System.out.println("server 读取数据异常");
}
}
/**
* 发送消息给所有客户端
*/
public void sendmsg() {
System.out.println(msg);
int num = mList.size();
for (int i = 0; i < num; i++) {
Socket mSocket = mList.get(i);
PrintWriter pout = null;
try {
pout = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(mSocket.getOutputStream())),
true);
pout.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
本文介绍了一个使用Java实现的简易聊天服务器程序。该程序利用多线程处理多个客户端连接请求,并通过Socket进行通信。服务器能够接收客户端消息并广播给所有在线用户。
2689

被折叠的 条评论
为什么被折叠?



