package tf
import java
import java
import java
import java
import
import
import java
import java
import ncurrent
import ncurrent
public class ChatServer {
private static final int PORT =
private static List<Socket> list = new ArrayList<Socket>(); // 保存連接對象
private ExecutorService exec;
private ServerSocket server;
public static void main(String[] args) {
new ChatServer();
}
public ChatServer() {
try {
server = new ServerSocket(PORT);
exec = Executors
System
Socket client = null;
while (true) {
client = server
list
exec
}
} catch (IOException e) {
e
}
}
static class ChatTask implements Runnable {
private Socket socket;
private BufferedReader br;
private PrintWriter pw;
private String msg;
public ChatTask(Socket socket) throws IOException {
this
br = new BufferedReader(new InputStreamReader(socket
msg =
+ list
sendMessage();
}
public void run() {
try {
while ((msg = br
if (msg
list
br
pw
msg =
+ list
socket
sendMessage();
break;
} else {
msg =
sendMessage();
}
}
} catch (IOException e) {
e
}
}
/**
* 群發消息給聊天室的所有人
*/
private void sendMessage() throws IOException {
System
for (Socket client : list) {
pw = new PrintWriter(client
pw
}
}
}
}
package tf
import java
import java
import java
import
import ncurrent
import ncurrent
public class ChatClient {
private static final int PORT =
private static ExecutorService exec = Executors
public static void main(String[] args) throws Exception {
new ChatClient();
}
public ChatClient() {
try {
Socket socket = new Socket(
exec
System
BufferedReader br = new BufferedReader(new InputStreamReader(socket
String msg;
while ((msg = br
System
}
} catch (Exception e) {
}
}
/**
* 客戶端線程獲取控制台輸入消息
*/
static class Sender implements Runnable {
private Socket socket;
public Sender(Socket socket) {
this
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System
PrintWriter pw = new PrintWriter(socket
String msg;
while (true) {
msg = br
pw
if (msg
pw
br
exec
break;
}
}
} catch (Exception e) {
e
}
}
}
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27478.html