安卓实现连接wesokcet

在build.gradle里引入依赖:

implementation 'org.java-websocket:Java-WebSocket:1.5.2'

在Androidmanifest.xml 文件里加入网络权限:

<uses-permission android:name="android.permission.INTERNET" />

代码:

package com.xmkjsoft.video_call;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

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

import java.net.URISyntaxException;


public class MainActivity extends AppCompatActivity {

    private MyWebSocketClient webSocketClient;



    // 默认无参数构造函数
    public MainActivity() {
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connectWebSocket();
    }

    private void connectWebSocket() {
        try {
            webSocketClient = new MyWebSocketClient("ws://192.168.28.218/ws/1233");
            webSocketClient.connect();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    // 内部类,用于处理 WebSocket 连接状态和消息
    private class MyWebSocketClient extends WebSocketClient {

        public MyWebSocketClient(String serverUri) throws URISyntaxException {
            super(new java.net.URI(serverUri));
        }

        @Override
        public void onOpen(ServerHandshake handshakedata) {
            // WebSocket 连接已打开
            System.out.println("WebSocket 连接已打开");
        }

        @Override
        public void onMessage(String message) {
            // 收到文本消息
            System.out.println("收到文本消息:" + message);
        }

        @Override
        public void onClose(int code, String reason, boolean remote) {
            // WebSocket 连接已关闭
            System.out.println("WebSocket 连接已关闭,code:" + code + ", reason:" + reason + ", remote:" + remote);
        }

        @Override
        public void onError(Exception ex) {
            // WebSocket 连接出错
            System.out.println("WebSocket 连接出错:" + ex.getMessage());
        }
    }
}

服务端代码:

package com.xmkjsoft.video_call_server.websocket;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;


import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

@CrossOrigin
@ServerEndpoint(value = "/ws/{userId}")
@Component
public class OnlineWebSocket {
    private Session session;
    private String userId;

    private static Set<OnlineWebSocket> onlineWebSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        onlineWebSocketSet.add(this);
        System.out.println("WebSocket 连接已建立,用户ID:" + userId);
    }

    @OnClose
    public void onClose(CloseReason reason) {
        onlineWebSocketSet.remove(this);
        System.out.println("WebSocket 连接已关闭,用户ID:" + userId);
        if (reason.getReasonPhrase().equals("EOFException")) {
            // 处理 EOFException 异常
            // 例如:重新建立连接或者通知用户连接已断开
            System.out.println("连接关闭原因:EOFException");
        }
    }


    @OnMessage
    public void onMessage(Session session, String message, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (!message.equals("ping")) {
            System.out.println("收到客户端,用户ID:" + userId + ",消息内容:" + message);
        } else {
            // 收到心跳回应,不做任何处理
        }
    }

}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值