public class MyMessage implements Serializable {// 序列化&&反序列化(用于被传输的对象)
public static final long serialVersionUID = 1l;
public static final int MES_TYPE_PLAIN = 1;//文本消息
public static final int MES_TYPE_UPDATE_CLIENTLIST = 2;//更新用户列表消息
public class signup extends JFrame{
private JTextField usename = new JTextField();//文本输入框
private JTextField password = new JTextField();
private JButton signup = new JButton("注册");//按钮
private JButton signin = new JButton("登陆");
public class ServerSocketTest {
ServerSocket server;
HashSet<Socket> clientSet = new HashSet<>();
public ServerSocketTest() {
try {
server = new ServerSocket(12345);
} catch (IOException e) {
e.printStackTrace();
}
}
public void work() {
int no = 0;//连接服务器的个数
try {
while (true) {
Socket client = server.accept();
clientSet.add(client);
SendUpdateClientList();
no++;
new ClientThread(client, no).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void SendUpdateClientList() {//发送用户变更的消息,用户退出和加入的监听
MyMessage mes = new MyMessage(true,MyMessage.MES_TYPE_UPDATE_CLIENTLIST);
mes.setClientList(getClientList());
massMes(mes);
}
public void massMes(MyMessage mes) {//群发消息
Iterator<Socket> it = clientSet.iterator();
while (it.hasNext()) {
sendMes(it.next(), mes);
}
}
public void singleMes(MyMessage mes){//单发消息
for(Socket s : clientSet){
if(s.getRemoteSocketAddress().toString().equals(mes.getIp())){//String判等必须用equals
sendMes(s, mes);
break;
}
}
}
public void sendMes(Socket s, MyMessage mes) {
ObjectOutputStream out;
try {
out = new ObjectOutputStream(s.getOutputStream());
out.writeObject(mes);
out.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public ArrayList<String> getClientList() {
ArrayList<String> list = null;
if (clientSet.size() > 0) {
list = new ArrayList<String>();
Iterator<Socket> it = clientSet.iterator();
int index = 0;
while (it.hasNext()) {
list.add(it.next().getRemoteSocketAddress().toString());
}
}
return list;
}
class ClientThread extends Thread {
Socket c;
int no;
public ClientThread(Socket c, int no) {
super();
this.c = c;
this.no = no;
}