Android笔记--WebSocket

这一节了解一下WebSocket的用法,WebSocket是一种基于TCP的全双工通信协议,通过它可以在客户端和服务器之间建立一个持久的连接,实现实时的双向数据传输。它的主要功能特点是允许服务器主动向客户端推送信息,同时也允许客户端主动向服务器发送信息。用法如下:

app下的gradle:

java 复制代码
implementation "org.java-websocket:Java-WebSocket:1.5.3"

服务端:

java 复制代码
import android.util.Log;
import com.foxek.usb_custom_hid_demo.UsbPlay;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DCWebSocketServer extends WebSocketServer {

    public static String TAG = "DCWebSocketServer";
    private Map<String, WebSocket> userMap = new HashMap<String, WebSocket>();

    public DCWebSocketServer(int port) {
        super(new InetSocketAddress(port));
    }

    public void sendMessageToUser(String message) {
        message = message;
        if (userMap == null || userMap.isEmpty()) return;
        Set<String> ketSet = userMap.keySet();
        for (String key : ketSet) {
            WebSocket clientSocket = userMap.get(key);
            if (clientSocket != null) {
                clientSocket.send(message);
            }
        }
    }


    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        String userHost = conn.getRemoteSocketAddress().getHostString();
        if(!userMap.containsKey(userHost)) {
            userMap.put(userHost,conn);
        }
        String res = getClientInfo(conn);
    }


    @Override
    protected boolean onConnect(SelectionKey key) {
        return super.onConnect(key);
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        String userHost = conn.getRemoteSocketAddress().getHostString();
        if (userMap.containsKey(userHost)) {
            userMap.remove(userHost);
        }
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        if(message != null && message.contains("ScanCode")) {
//            sendMessageToUser(message);
        }

    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
       
    }

    @Override
    public void onStart() {
    }

    private String getClientInfo(WebSocket conn) {
        return conn.getRemoteSocketAddress().getHostString()
                +":"+  conn.getRemoteSocketAddress().getPort();
    }
}
java 复制代码
import android.util.Log;
import org.java_websocket.WebSocket;
import java.util.HashMap;
import java.util.Map;

public class ServerSocketManager {
    public static String TAG = "ServerSocketManager";
    private final int SOCKET_PORT = 8888;
    private DCWebSocketServer dcWebSocketServer;
    private Map<WebSocket, String> userMap = new HashMap<WebSocket, String>();

    public ServerSocketManager() {
        this.dcWebSocketServer =  new DCWebSocketServer(SOCKET_PORT);
    }

    private static class ServerSocketManagerHolder {
        private static final ServerSocketManager INSTANCE = new ServerSocketManager();
    }

    public static  ServerSocketManager getInstance() {
        return ServerSocketManagerHolder.INSTANCE;
    }

    public void sendMessageToAll(String message) {
        dcWebSocketServer.sendMessageToUser(message);
    }

    public boolean start() {
        try {
            dcWebSocketServer.start();
            dcWebSocketServer.setReuseAddr(true);
           
            return true;
        } catch (Exception e) {
           
            e.printStackTrace();
            return false;
        }
    }

    public boolean stop() {
        try {
            dcWebSocketServer.stop();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}

客户端:

java 复制代码
import android.util.Log;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

public class DCSocketManagerClient extends WebSocketClient {
    public static String TAG = "DCSocketManagerClien";
    private static volatile DCSocketManagerClient client = null;

    public static DCSocketManagerClient getInstance(URI uri) {
        if (client == null) {
            synchronized (DCSocketManagerClient.class) {
                if (client == null) {
                    client = new DCSocketManagerClient(uri);
                }
            }
        }
        return client;
    }

    public DCSocketManagerClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
       
    }

    @Override
    public void onMessage(String message) {
       
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        
    }

    @Override
    public void onError(Exception ex) {
       
    }
}

启动服务端:

Kotlin 复制代码
 serverSocketManager = ServerSocketManager.getInstance()
 serverSocketManager!!.start()

启动客户端:

Kotlin 复制代码
val uri = URI.create("ws://127.0.0.1:8888")
clientSocketManager = DCSocketManagerClient.getInstance(uri)
 try {
          clientSocketManager?.connectBlocking()
        } catch (e: Exception) {
        
           e.printStackTrace()
     }

客户端发送消息:

java 复制代码
  if (clientSocketManager != null) {
      clientSocketManager!!.send("Java Coffee")
  }

服务端发送消息:

java 复制代码
    if (serverSocketManager != null) {
          serverSocketManager!!.sendMessageToAll("Drink Coffee From ServerMsg")
    }
相关推荐
傻啦嘿哟24 分钟前
代理IP在后端开发中的应用与后端工程师的角色
网络·网络协议·tcp/ip
Red Red28 分钟前
网安基础知识|IDS入侵检测系统|IPS入侵防御系统|堡垒机|VPN|EDR|CC防御|云安全-VDC/VPC|安全服务
网络·笔记·学习·安全·web安全
向阳12181 小时前
Dubbo HTTP接入之triple协议
网络协议·http·dubbo
贰十六1 小时前
笔记:Centos Nginx Jdk Mysql OpenOffce KkFile Minio安装部署
笔记·nginx·centos
知兀1 小时前
Java的方法、基本和引用数据类型
java·笔记·黑马程序员
天天进步20152 小时前
Vue+Springboot用Websocket实现协同编辑
vue.js·spring boot·websocket
醉陌离2 小时前
渗透测试笔记——shodan(4)
笔记
Estar.Lee3 小时前
时间操作[计算时间差]免费API接口教程
android·网络·后端·网络协议·tcp/ip
LateBloomer7773 小时前
FreeRTOS——信号量
笔记·stm32·学习·freertos
legend_jz3 小时前
【Linux】线程控制
linux·服务器·开发语言·c++·笔记·学习·学习方法