1 maven java
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.12</version>
</dependency>
2 爲了使服務運行啓動須要實現 ApplicationListener 重寫裏面的方法 onApplicationEvent
import com.corundumstudio.socketio.*; import com.corundumstudio.socketio.listener.ConnectListener; import com.corundumstudio.socketio.listener.DataListener; import com.corundumstudio.socketio.listener.DisconnectListener; import com.corundumstudio.socketio.listener.ExceptionListenerAdapter; import io.netty.channel.ChannelHandlerContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Service; @Service public class SocketIoServer implements ApplicationListener<ContextRefreshedEvent> { private SocketIOServer server; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { //端口 int WSS_PORT=9001; //服務器ip String WSS_HOST="127.0.0.1"; if( server== null) { Configuration config = new Configuration(); //服務器ip config.setHostname(WSS_HOST); config.setPort(WSS_PORT); //該處進行身份驗證h config.setAuthorizationListener(new AuthorizationListener() { @Override public boolean isAuthorized(HandshakeData handshakeData) { //http://localhost:8081?username=test&password=test //例若是使用上面的連接進行connect,可使用以下代碼獲取用戶密碼信息 //String username = data.getSingleUrlParam("username"); //String password = data.getSingleUrlParam("password"); return true; } }); config.setExceptionListener(new ExceptionListenerAdapter() { @Override public boolean exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception { System.out.println("錯誤:\n" + e.getMessage()); ctx.close(); return true; } }); server = new SocketIOServer(config); //添加連接事件監聽 server.addConnectListener(new ConnectListener() { @Override public void onConnect(SocketIOClient client) { String clientId = client.getHandshakeData().getSingleUrlParam("clientid"); SocketIOClient si = ChatServerPool.getSocketIOClientByClientID(clientId); //這個客戶端有沒有鏈接過 // 若是沒有鏈接信息、則新建會話信息 if (si == null) { //在線數加1 //將會話信息更新保存至集合中 ChatServerPool.addUser(clientId, client); } //在線數減1 System.out.println("socket 鏈接、sessionId:" + client.getSessionId() + "、clientId:" + clientId+",當前人數:"+ChatServerPool.onLineCount.get() ); } }); //添加銷燬連接事件監聽 server.addDisconnectListener(new DisconnectListener() { @Override public void onDisconnect(SocketIOClient client) { String clientId = client.getHandshakeData().getSingleUrlParam("clientid"); ChatServerPool.removeUser(clientId); //在線數減1 System.out.println("socket 斷開鏈接、sessionId:" + client.getSessionId() + "、clientId:" + clientId+",當前人數:"+ChatServerPool.onLineCount.get() ); } }); //添加發送消息事件監聽 server.addEventListener("message_event", MessageInfo.class, new DataListener<MessageInfo>() { @Override public void onData(SocketIOClient client, MessageInfo data, AckRequest ackSender) throws Exception { MessageInfo sendData = new MessageInfo(); sendData.setSourceClientId(data.getSourceClientId()); sendData.setTargetClientId(data.getTargetClientId()); sendData.setMsg(data.getMsg()); // 向當前會話發送信息 ChatServerPool.sendMessageToUserBySocketClient(client,"message_event",sendData.getMsg().toString()); // 向目標會話發送信息 ChatServerPool.sendMessageToUser(data.getTargetClientId(),"message_event",sendData.getMsg().toString()); } }); //須要執行的邏輯代碼,當spring容器初始化完成後就會執行該方法。 server.start(); System.out.println("start****************************server***"+WSS_PORT+"***********************end"); } } }
3 web
ChatServerPool.java
import com.corundumstudio.socketio.SocketIOClient; import java.util.Collection; import java.util.Set; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicInteger; public class ChatServerPool { //會話集合 private static final ConcurrentSkipListMap<String, SocketIOClient> webSocketMap = new ConcurrentSkipListMap<>(); //靜態變量,用來記錄當前在線鏈接數。(原子類、線程安全) public static AtomicInteger onLineCount = new AtomicInteger(); /** * SocketIOClient */ public static SocketIOClient getSocketIOClientByClientID(String clientID){ SocketIOClient sc = webSocketMap.get(clientID); return sc; } /** * 向鏈接池中添加鏈接 */ public static void addUser(String clientID, SocketIOClient conn){ if(conn !=null) { webSocketMap.put(clientID, conn); //添加鏈接 onLineCount.incrementAndGet(); } } /** * 獲取全部的在線用戶 * @return */ public static Collection<String> getOnlineUser(){ Set<String> setUsers = webSocketMap.keySet(); return setUsers; } /** * 移除鏈接池中的鏈接 */ public static boolean removeUser(String clientID){ if(webSocketMap.containsKey(clientID)){ webSocketMap.remove(clientID); //移除鏈接 return true; }else{ return false; } } /** * 向特定的用戶發送數據 */ public static void sendMessageToUser(String clientId,String event,String msg){ if(webSocketMap.containsKey(clientId) && !"".equals(msg)){ webSocketMap.get(clientId).sendEvent(event, msg); } } /** * 向特定的用戶發送數據 */ public static void sendMessageToUserBySocketClient(SocketIOClient conn,String event,String msg){ if(conn !=null && !"".equals(msg)){ conn.sendEvent(event, msg); } } /** * 向全部的用戶發送消息 * @param message */ public static void sendMessageAll(String event,String message){ Collection<SocketIOClient> cs = webSocketMap.values(); synchronized (cs) { if(event !=null && !"".equals(event)){ for (SocketIOClient conn : cs) { if(conn != null){ conn.sendEvent(event,message); } } }else{ for (SocketIOClient conn : cs) { if(conn != null){ conn.sendEvent(message); } } } } } }
4 MessageInfo.javaspring
public class MessageInfo { private String targetClientId ; private String sourceClientId; private Object msg ; public String getTargetClientId() { return targetClientId; } public void setTargetClientId(String targetClientId) { this.targetClientId = targetClientId; } public String getSourceClientId() { return sourceClientId; } public void setSourceClientId(String sourceClientId) { this.sourceClientId = sourceClientId; } public Object getMsg() { return msg; } public void setMsg(Object msg) { this.msg = msg; } }
4 script
<script> var clientId='sys',targetId='sys001' ; var socket = io.connect('http://localhost:9001?clientid=sys'); socket.on('connect', function () { showMsg(':<span class="connect-msg">成功鏈接到服務器!</span>'); }); socket.on('message_event', function (data) { showMsg('<br /><span class="username-msg">' + data.sourceClientId + ':</span> ' + data.msg); }); socket.on('disconnect', function () { showMsg(':<span class="disconnect-msg">服務已斷開!</span>'); }); function sendDisconnect() { socket.disconnect(); } function sendMessage() { var message = $('#msg').val(); $('#msg').val(''); var jsonObject = { sourceClientId: clientId, targetClientId: targetId, msg: message }; socket.emit('message_event', jsonObject); } function showMsg(message) { var currentTime = "<span class='time'>2019-01-01</span>"; var element = $("<div>" + currentTime + "" + message + "</div>"); $('#console').append(element); } </script>