socket.io是一個(gè)netty.socket node版的java實(shí)現(xiàn)版,其性能優(yōu)于webSocket等socket技術(shù),socket.io有nameSpace等贱田,分區(qū)方式,比較靈活。
服務(wù)端實(shí)現(xiàn)
maven
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.12</version>
</dependency>
prop
originHost為socket客戶端的地址,serverHost請(qǐng)使用ip纲堵,lz在使用過程中嘗試過使用localhost,但服務(wù)未能調(diào)用成功闰渔。
#socketIO
wss.server.port=9093
wss.server.host=0.0.0.0
wss.origin.host=http://localhost:8080
socketConfig
socketIoConfig用于生產(chǎn)bean席函,在socketService等其他地方調(diào)用該SocketIOServer的bean
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author nickBi
* create on 2018/7/5.
*/
@Configuration
public class SocketIoConfig {
@Value("${wss.server.host}")
private String host;
@Value("${wss.server.port}")
private Integer port;
@Value("${wss.origin.host}")
private String originHost;
@Bean
public SocketIOServer socketIOServer() {
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
config.setHostname(host);
config.setPort(port);
config.setOrigin(originHost);
final SocketIOServer server = new SocketIOServer(config);
return server;
}
@Bean
public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
return new SpringAnnotationScanner(socketServer);
}
}
socketRunner,在springboot啟動(dòng)項(xiàng)目的時(shí)候冈涧,啟動(dòng)socket服務(wù)
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* @author nickBi
* create on 2018/7/5.
*/
@Component
public class SocketRunner implements CommandLineRunner {
@Autowired
private SocketIOServer server;
@Override
public void run(String... args) throws Exception {
server.start();
}
}
SocketService
mport com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author nickBi
* create on 2018/7/5.
*/
@Service
public class SocketService {
private static final Logger LOGGER = LoggerFactory.getLogger(SocketService.class);
@Autowired
private SocketIOServer server;
private static Map<String, SocketIOClient> clientsMap = new HashMap<String, SocketIOClient>();
/**
* 添加connect事件茂附,當(dāng)客戶端發(fā)起連接時(shí)調(diào)用,本文中將clientid與sessionid存入數(shù)據(jù)庫
* //方便后面發(fā)送消息時(shí)查找到對(duì)應(yīng)的目標(biāo)client,
*
* @param client
*/
@OnConnect
public void onConnect(SocketIOClient client) {
String uuid = client.getSessionId().toString();
clientsMap.put(uuid, client);
LOGGER.debug("IP: " + client.getRemoteAddress().toString() + " UUID: " + uuid + " 設(shè)備建立連接");
}
/**
* 添加@OnDisconnect事件督弓,客戶端斷開連接時(shí)調(diào)用营曼,刷新客戶端信息
*/
@OnDisconnect
public void onDisconnect(SocketIOClient client) {
String uuid = client.getSessionId().toString();
clientsMap.remove(uuid);
LOGGER.debug("IP: " + client.getRemoteAddress().toString() + " UUID: " + uuid + " 設(shè)備斷開連接");
}
/**
* 給所有連接客戶端推送消息
*
* @param eventType 推送的事件類型
* @param message 推送的內(nèi)容
*/
public void sendMessageToAllClient(String eventType, String message) {
Collection<SocketIOClient> clients = server.getAllClients();
for (SocketIOClient client : clients) {
client.sendEvent(eventType, message);
}
}
}
客戶端
<!DOCTYPE html>
<html>
<head>
<title>Demo Chat</title>
<link href="bootstrap.css" rel="stylesheet">
<style>
body {
padding:20px;
}
.console {
height: 400px;
overflow: auto;
}
.username-msg {color:orange;}
.connect-msg {color:green;}
.disconnect-msg {color:red;}
.send-msg {color:#888}
</style>
<script src="js/socket.io/socket.io.js"></script>
<script src="js/moment.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
var userName1 = 'user1_' + Math.floor((Math.random()*1000)+1);
var chat1Socket = io.connect('http://localhost:9092');
function connectHandler(parentId) {
return function() {
output('<span class="connect-msg">Client has connected to the server!</span>', parentId);
}
}
function messageHandler(parentId) {
return function(data) {
output('<span class="username-msg">' + data.userName + ':</span> ' + data.message, parentId);
}
}
function disconnectHandler(parentId) {
return function() {
output('<span class="disconnect-msg">The client has disconnected!</span>', parentId);
}
}
function sendMessageHandler(parentId, userName, chatSocket) {
var message = $(parentId + ' .msg').val();
$(parentId + ' .msg').val('');
var jsonObject = {'@class': 'com.corundumstudio.socketio.demo.ChatObject',
userName: userName,
message: message};
chatSocket.json.send(jsonObject);
}
chat1Socket.on('connect', connectHandler('#chat1'));
chat1Socket.on('message', messageHandler('#chat1'));
chat1Socket.on('disconnect', disconnectHandler('#chat1'));
function sendDisconnect1() {
chat1Socket.disconnect();
}
function sendMessage1() {
sendMessageHandler('#chat1', userName1, chat1Socket);
}
function output(message, parentId) {
var currentTime = "<span class='time'>" + moment().format('HH:mm:ss.SSS') + "</span>";
var element = $("<div>" + currentTime + " " + message + "</div>");
$(parentId + ' .console').prepend(element);
}
$(document).keydown(function(e){
if(e.keyCode == 13) {
$('#send').click();
}
});
</script>
</head>
<body>
<h1>Namespaces demo chat</h1>
<br/>
<div id="chat1" style="width: 49%; float: left;">
<h4>chat1</h4>
<div class="console well">
</div>
<form class="well form-inline" onsubmit="return false;">
<input class="msg input-xlarge" type="text" placeholder="Type something..."/>
<button type="button" onClick="sendMessage1()" class="btn" id="send">Send</button>
<button type="button" onClick="sendDisconnect1()" class="btn">Disconnect</button>
</form>
</div>
</body>
</html>