java spring webSocket应用
作者:binWebSocket协议是基于TCP的一种新的网络协议,它实现了浏览器与服务器全双工(full-duplex)通信,即运行服务器主动发送消息给客户端,通常我们的http访问,都只能是又客户端访问驱动
下面将演示一下如何使用java spring搭建一个简单的服务端点
如果你对前端如何实现一个websocket客户端感兴趣,作为关联学习你可以查看(http://zengbingo.com/?p=1494)
首先为要要加入关于WebSocket的依赖,
<dependency> <groupId>org.springframwork.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
然后我们开始建立简单的WebSocket服务端点,配置文件
@Configuration
public class WebSocketConfig {
//创建服务器端点
@Bean
public ServerEndPointExporter serverEndPointExporter() {
return new ServerEndPointExporter();
}
}
有了上面的这个Bean,就可以使用@ServerEndPoint定义一个端点服务类:
@ServerEndPoint("/ws")
@Service
public class WebSocketServiceImpl {
//concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServiceImpl对象, 下面会用来群发消息
private static CopyOnWriteArraySet<WebSocketServiceImpl> webSokcetSet = new CopyOnWriteArraySet<>();
//某个客户端的链接对话
private Session session;
//当打开新链接时执行
@OnOpen
public viod onOpen(Session session) {
this.session = session;
//添加进Set中,这样就知道总共有哪些在链接着
webSocketSet.add(this);
System.out.println("有新的链接加入了");
try {
sendMessage("你好,新成员");
}catch (IOException e) {
System.out.println("IO异常");
}
}
//发送消息给客户端
private void sendMessage(String message) throw IOException {
this.session.getBasicRemote().sentText(message);
}
//收到客户端发来的消息
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("接收到客户端发来的消息");
}
//当链接关闭时执行
@OnClose
public viod onClose(){
webSocketSet.remove(this); //从set中删除
System.out.println("有一个链接关闭了");
}
@OnError
public void onError(Session session, Throwable error){
System.out.println("有一个链接异常了");
error.printStackTrace();
}
//演示如何群发消息给客户端
public void publishMessage(){
webSokcetSet.forEach( eachConnect -> {
eachConnect.sendMessage("这是一条群发消息");
})
}
}