WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
优点:双向通信、事件驱动、异步、使用ws或wss协议的客户端能够真正实现意义上的推送功能。
缺点:少部分浏览器不支持。
示例:社交聊天(微信、QQ)、弹幕、多玩家玩游戏、协同编辑、股票基金实时报价、体育实况更新、视频会议/聊天、基于位置的应用、在线教育、智能家居等高实时性的场景。
后台springboot +Android客户端实现即时聊天:
springboot:
项目结构:
导入依赖:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
配置类WebSocketConfig,这里开启了配置之后springboot才会去扫描对应的注解。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
编写端点服务类
接下来在 config 包下创建一个 WebSocket 配置类 WebSocketConfiguration,在配置类上加入注解 @EnableWebSocket,表明开启 WebSocket,内部实例化 ServerEndpointExporter 的 Bean,该 Bean 会自动注册 @ServerEndpoint 注解声明的端点,代码如下:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.yang.springboot_mtbatis.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
//注册成组件
@Component
//定义websocket服务器端,它的功能主要是将目前的类定义成一个websocket服务器端。注解的值将被用于监听用户连接的终端访问URL地址
@ServerEndpoint("/websocket/{userId}")
//如果不想每次都写private final Logger logger = LoggerFactory.getLogger(当前类名.class); 可以用注解@Slf4j;可以直接调用log.info
@Slf4j
public class WebSocket {
@Autowired
UserService userService;
//实例一个session,这个session是websocket的session
private Session session;
/**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();
/**接收userId*/
private String userId="";
private static int onlineCount = 0;
//前端请求时一个websocket时
@OnOpen
public void onOpen(Session session,@PathParam("userId") String userId) {
this.session = session;
this.userId=userId;
if(webSocketMap.containsKey(userId)){
webSocketMap.remove(userId);
webSocketMap.put(userId,this);
//加入set中
}else{
webSocketMap.put(userId,this);
//加入set中
addOnlineCount();
//在线数加1
}
}
//前端关闭时一个websocket时
@OnClose
public void onClose() {
if(webSocketMap.containsKey(userId)){
webSocketMap.remove(userId);
//从set中删除
subOnlineCount();
}
log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
}
StringBuilder stringBuilder;
//前端向后端发送消息
@OnMessage
public void onMessage(String message) {
log.info("用户消息:"+userId+",报文:"+message);
//可以群发消息
//消息保存到数据库、redis
if(!message.isEmpty()){
try {
//解析发送的报文
JSONObject jsonObject = JSON.parseObject(message);
//追加发送人(防止串改)
jsonObject.put("fromUserId",this.userId);
String toUserId=jsonObject.getString("toUserId");
//传送给对应toUserId用户的websocket
if(!toUserId.isEmpty()&&webSocketMap.containsKey(toUserId)){
sendMessage(jsonObject.toJSONString());
}else{
log.error("请求的userId:"+toUserId+"不在该服务器上");
//否则不在这个服务器上,发送到mysql或者redis
}
}catch (Exception e){
e.printStackTrace();
}
}
}
//新增一个方法用于主动向客户端发送消息
public void sendMessage(String message) {
log.info("【websocket消息】广播消息, message={}", message);
try {
this.session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
/** * 发送自定义消息 * */
public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
log.info("发送消息到:"+userId+",报文:"+message);
if(!userId.isEmpty()&&webSocketMap.containsKey(userId)){
webSocketMap.get(userId).sendMessage(message);
}else{
log.error("用户"+userId+",不在线!");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
}
其中,@ServerEndpoint(“/websocket/{userId}”)表示让 Spring 创建 WebSocket 的服务端点,其中请求地址是 /websocket/{userId}。
另外 WebSocket 一共有四个事件,分别对应 JSR-356 定义的 @OnOpen、@OnMessage、@OnClose、@OnError 注解。
@OnOpen:标注客户端打开 WebSocket 服务端点调用方法
@OnClose:标注客户端关闭 WebSocket 服务端点调用方法
@OnMessage:标注客户端发送消息,WebSocket 服务端点调用方法
@OnError:标注客户端请求 WebSocket 服务端点发生异常调用方法
Android客户端:
新建一个界面:
xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户id:"
android:textColor="@color/xui_config_color_black"/>
<EditText
android:id="@+id/et_user_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1"/>
LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="websocket:"
android:textColor="@color/xui_config_color_black"/>
<TextView
android:id="@+id/tv_message"
android:layout_width="match_parent"
android:layout_height="300dp"
android:singleLine="false"
android:scrollbars="vertical"
android:text="111"/>
<EditText
android:id="@+id/et_send_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"/>
<Button
android:id="@+id/btn_clear"
android:layout_marginLeft="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="清除"/>
<Button
android:id="@+id/btn_create"
android:layout_marginLeft="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="创建"/>
LinearLayout>
LinearLayout>
java类:
package com.jqwl.myapp.fragment;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jqwl.myapp.core.BaseFragment;
import com.jqwl.myapp.databinding.FragmentWebsocketBinding;
import com.jqwl.myapp.httpapi.HttpApi;
import com.jqwl.myapp.httpapi.RetrofitManager;
import com.jqwl.myapp.utils.XToastUtils;
import com.jqwl.myapp.utils.websocket.JWebSocketClient;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.util.Date;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@Page(name = "WebSocket 实现Android客户端与服务器的长连接", anim = CoreAnim.slide)
public class WebSocketFragment extends BaseFragment<FragmentWebsocketBinding> {
FragmentWebsocketBinding binding;
TextView tv_message;
EditText et_send_message;
EditText et_user_id;
Button btn_send;
Button btn_clear;
Button btn_create;
private JWebSocketClient client;
private StringBuilder sb = new StringBuilder();
@NonNull
@Override
protected FragmentWebsocketBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
binding = FragmentWebsocketBinding.inflate(inflater,container,false);
tv_message = binding.tvMessage;
et_send_message = binding.etSendMessage;
btn_send = binding.btnSend;
btn_clear = binding.btnClear;
et_user_id = binding.etUserId;
btn_create = binding.btnCreate;
return binding;
}
@Override
protected void initViews() {
createWebSocketClient(et_user_id.getText().toString().trim());
}
private void createWebSocketClient(String userId){
// URI uri = URI.create("ws://172.25.204.62:8082/websocket/"+userId);
URI uri = URI.create("ws://192.168.0.109:8082/websocket/"+userId);
client = new JWebSocketClient(uri){
@Override
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
sb.append("onOpen at time:");
sb.append(new Date());
sb.append("服务器状态:");
sb.append(handshakedata.getHttpStatusMessage());
sb.append("\n");
tv_message.setText(sb.toString());
}
@Override
public void onMessage(String message) {
super.onMessage(message);
Message handlerMessage = Message.obtain();
handlerMessage.obj = message;
handler.sendMessage(handlerMessage);
}
@Override
public void onClose(int code, String reason, boolean remote) {
super.onClose(code, reason, remote);
sb.append("onClose at time:");
sb.append(new Date());
sb.append("\n");
sb.append("onClose info:");
sb.append(code);
sb.append(reason);
sb.append(remote);
sb.append("\n");
tv_message.setText(sb.toString());
}
@Override
public void onError(Exception ex) {
super.onError(ex);
sb.append("onError at time:");
sb.append(new Date());
sb.append("\n");
sb.append(ex);
sb.append("\n");
tv_message.setText(sb.toString());
}
};
try {
client.connectBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
XToastUtils.error(e+"");
}
}
@Override
protected void initListeners() {
super.initListeners();
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(client.isClosed() || client.isClosing()){
XToastUtils.info("Client正在关闭");
client.connect();
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("message",et_send_message.getText().toString().trim());
jsonObject.put("toUserId",et_user_id.getText().toString().trim());
client.send(jsonObject.toJSONString());
sb.append("客户端发送消息:");
sb.append(new Date());
sb.append("\n");
sb.append(et_send_message.getText().toString().trim());
sb.append("\n");
tv_message.setText(sb.toString());
et_send_message.setText("");
}
});
btn_clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sb = new StringBuilder();
tv_message.setText(sb);
}
});
btn_create.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pushToService();
}
});
}
private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
sb.append("服务器返回数据:");
sb.append(msg.obj.toString());
sb.append("\n");
tv_message.setText(sb.toString());
return true;
}
});
public void pushToService() {
String message = "hhhhh";
JSONObject data = new JSONObject();
JSONObject param = new JSONObject();
data.put("message",message);
// param.put("userId","qqq");
// JSONObject requestBody = new JSONObject();
// requestBody.put("data",data);
param.put("data", data);
HttpApi api= RetrofitManager.initRetrofit(RetrofitManager.localhost).create(HttpApi.class);
retrofit2.Call<JSONObject> resultcall=api.webSocketRpc(param);
resultcall.enqueue(new Callback<JSONObject>() {
//请求成功时回调
@Override
public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
if(response.isSuccessful()){
JSONObject json = response.body();
}else{
XToastUtils.error("失败");
}
}
//请求失败时候的回调
@Override
public void onFailure(Call<JSONObject> call, Throwable throwable) {
XToastUtils.error("服务器忙!请稍后再试");
}
});
}
}