1. 后台 启动类,执行main方法启动
package com.fh;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Date;
import net.sf.json.JSONObject;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
/**
* @author FH
* from fhadmin.cn
* 2021-5-16
*/
public class ChatServer extends WebSocketServer{
public ChatServer(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
}
public ChatServer(InetSocketAddress address) {
super(address);
}
/**
* 触发连接事件
*/
@Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
//this.sendToAll( "new connection: " + handshake.getResourceDescriptor() );
//System.out.println( conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
/**
* 触发关闭事件
*/
@Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
userLeave(conn);
}
/**
* 客户端发送消息到服务器时触发事件
*/
@Override
public void onMessage(WebSocket conn, String message){
message = message.toString();
if(null != message && message.startsWith("FHadmin313596790")){
this.userjoin(message.replaceFirst("FHadmin313596790", ""),conn);
}if(null != message && message.startsWith("LeaveFHadmin313596790")){
this.userLeave(conn);
}if(null != message && message.contains("fhadmin886")){
String toUser = message.substring(message.indexOf("fhadmin886")+10, message.indexOf("fhfhadmin888"));
message = message.substring(0, message.indexOf("fhadmin886")) +"[私信] "+ message.substring(message.indexOf("fhfhadmin888")+12, message.length());
ChatServerPool.sendMessageToUser(ChatServerPool.getWebSocketByUser(toUser),message);//向所某用户发送消息
ChatServerPool.sendMessageToUser(conn, message);//同时向本人发送消息
}else{
ChatServerPool.sendMessage(message.toString());//向所有在线用户发送消息
}
}
public void onFragment( WebSocket conn, Framedata fragment ) {
}
/**
* 触发异常事件
*/
@Override
public void onError( WebSocket conn, Exception ex ) {
ex.printStackTrace();
if( conn != null ) {
//some errors like port binding failed may not be assignable to a specific websocket
}
}
/**
* 用户加入处理
* @param user
*/
public void userjoin(String user, WebSocket conn){
JSONObject result = new JSONObject();
result.element("type", "user_join");
result.element("user", "<a onclick=\"toUserMsg('"+user+"');\&#