pom.xml
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.7</version>
</dependency>
SocketIoService.java
@Service("socketIoService")
public class SocketIoService {
static SocketIOServer server;
static Map<String,SocketIOClient> clientsMap = new HashMap<String, SocketIOClient>();
public void startServer()throws InterruptedException{
Configuration config = new Configuration();
//服务器主机ip
String hostName = "127.0.0.1";
config.setHostname(hostName);
//端口
int socketPort = 3000;
config.setPort(socketPort);
config.setMaxFramePayloadLength(1024 * 1024);
config.setMaxHttpContentLength(1024 * 1024);
server = new SocketIOServer(config);
//添加客户端连接事件
server.addConnectListener(new ConnectListener() {
@Override
public void onConnect(SocketIOClient client) {
String sa = client.getRemoteAddress().toString();
String clientIp = sa.substring(1,sa.indexOf(":"));//获取设备ip
/*System.out.println(clientIp+"-------------------------"+"客户端已连接");*/
Map params = client.getHandshakeData().getUrlParams();
//获取客户端连接的uuid参数
Object object = params.get("uuid");
String uuid = "";
if(object != null){
uuid = ((List<String>)object).get(0);
//将uuid和连接客户端对象进行绑定
clientsMap.put(uuid,client);
}
//给客户端发送消息
client.sendEvent("connect_msg",clientIp+"客户端你好,我是服务端,能帮助你吗?");
}
});
server.start();
Thread.sleep(Integer.MAX_VALUE);
server.stop();
}
/**
* 给所有连接客户端推送消息
* @param eventType 推送的事件类型
* @param message 推送的内容
*/
public void sendMessageToAllClient(String eventType,String message){
Collection<SocketIOClient> clients = server.getAllClients();
for(SocketIOClient client: clients){
client.sendEvent(eventType,message);
}
}
/**
* 停止服务
*/
public void stopServer(){
if(server != null){
server.stop();
server = null;
}
}
public static SocketIOServer getServer() {
return server;
}
}
TestController.java
//启动socket 服务
@RequestMapping(value = "startServer.do")
public void startServer(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Origin", "*");
try {
if (serviceIo.getServer() == null) {
new Thread(new Runnable() {
@Override
public void run() {
try {
serviceIo.startServer();
} catch (Exception e) {
logger.error(String.valueOf(e));
}
}
}).start();
}
} catch (Exception e) {
logger.error(String.valueOf(e));
}
}
//发送消息
@RequestMapping(value = "sendMsg.do")
public void sendMsg(HttpServletRequest request) {
serviceIo.sendMessageToAllClient("advert_data", request.getParameter("msg"));
}
test.jsp
<script type="text/javascript" src="socket.io.js"></script>
<script>
var socketUrl = "http://127.0.0.1/startServer.do";
$.ajax({
url:socketUrl,
type:'get',
success:function(){
}
});
var socket = io.connect('http://127.0.0.1:3000');
socket.on('advert_data',function(data){
console.log(data);
});
</script>
socket.io.js (90 KB)