1,基于Spring boot + websokcet搭建一个简易的用于android及时的服务器
1、环境:IDEA
DEA 全称 IntelliJ IDEA 是java编程语言开发的集成环境就不讲如何搭建了网上一大堆 至于websokcet协议 不是本文重点,想要深入的可以自行Google。话不多说进入正题
File ➡new➡Project
- Artifact 内容要小写
- 在Dependencies中搜索Websocket并添加
- - 接着更改自己的项目目录然后finsh就行了
二、创建WebConfig类
/**
* 配置webSocket并开启
*/
@Configuration
public class WebConfig{
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
三、创建WebSocketServer类
/**
* 采用的是websocket地址+客户端名 用于识别连接的客户端
*/
@ServerEndpoint( "/websocket/{username}")
@Component
public class WebSocketServer {
//存储客户端,这个对象存储是安全的
private static ConcurrentHashMap<String,Session> clients = new ConcurrentHashMap<String,Session>();
//客户端标识
private String username;
private Log mLog = LogFactory.getLog(WebSocketServer.class);
//FLAG
private static final String FLAG = "WebSocket";
//客户端连接成功会触发这个方法
@OnOpen
public void onOpen(@PathParam("username")String username, Session session) throws IOException {
this.username = username;
//与客户端连接的会话用于发送数据
//保存会话
clients.put(username,session);
mLog.info(username + " :连接成功" );
}
//客户端断开连接会触发这个方法
@OnClose
public void onClose(){
//移除会话
clients.remove(this);
System.out.println(username+": 断开连接");
}
//收到客户端接收的消息触发这个方法
@OnMessage
public void onMessage(String message,Session session){
mLog.info("收到 "+ username +": 发送的信息:"+message);
//执行自己收到消息的逻辑
}
//客户端连接错误会触发这个方法
@OnError
public void onError(Session session,Throwable error){
error.printStackTrace();
}