文件:http://pan.baidu.com/share/link?shareid=835462713&uk=185595768
MyServerSocket..java
public class MyServerSocket {
public static void main(String[] args) {
//新建一个线程,防止阻塞主线程
new ServerListener().start();
}
}
ServerListener.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JOptionPane;
public class ServerListener extends Thread {
@Override
public void run() {
//1-65535
try {
ServerSocket serverSocket = new ServerSocket(12345);
while (true) {
//accept()会阻塞主线程,故要开一个新的线程处理
Socket socket = serverSocket.accept();
//建立连接
JOptionPane.showMessageDialog(null, "有客户端链接到了本机的12345端口");
//将socket传递给新的线程
ChatSocket cs = new ChatSocket(socket);
cs.start();
ChatManager.getChatManager().add(cs);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ChatSocket.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
public class ChatSocket extends Thread {
Socket socket;
public ChatSocket(Socket s){
this.socket = s;
}
public void out(String out) {
try {
socket.getOutputStream().write((out+"\n").getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("断开了一个客户端链接");
ChatManager.getChatManager().remove(this);
e.printStackTrace();
}
}
@Override
public void run() {
out("你已经连接到本服务器了");
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(
socket.getInputStream(),"UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
ChatManager.getChatManager().publish(this, line);
}
br.close();
System.out.println("断开了一个客户端链接");
ChatManager.getChatManager().remove(this);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("断开了一个客户端链接");
ChatManager.getChatManager().remove(this);
e.printStackTrace();
}
}
}
ChatManager.java
package com.jikexueyuan.testmysetversocket.main;
import java.util.Vector;
public class ChatManager {
private ChatManager(){}
private static final ChatManager cm = new ChatManager();
public static ChatManager getChatManager() {
return cm;
}
//用于储存管理新建的每一个socket线程
Vector<ChatSocket> vector = new Vector<ChatSocket>();
public void add(ChatSocket cs) {
vector.add(cs);
}
public void remove(ChatSocket cs) {
vector.remove(cs);
}
public void publish(ChatSocket cs,String out) {
for (int i = 0; i < vector.size(); i++) {
ChatSocket csChatSocket = vector.get(i);
if (!cs.equals(csChatSocket)) {
csChatSocket.out(out);
}
}
}
}