Jump to content

Hello visitors, welcome to the Hacker World Forum!

Red Team 1949  (formerly CHT Attack and Defense Team) In this rapidly changing Internet era, we maintain our original intention and create the best community to jointly exchange network technologies. You can obtain hacker attack and defense skills and knowledge in the forum, or you can join our Telegram communication group to discuss and communicate in real time. All kinds of advertisements are prohibited in the forum. Please register as a registered user to check our usage and privacy policy. Thank you for your cooperation.

TheHackerWorld Official

开发一个简单的Android聊天软件

Featured Replies

Posted

开发一个简单的Android聊天软件,需要将开发一个Android应用,以及服务端程序。
客户端登录后初始化socket长连接,向服务端发起链接,服务端收到客户端链接,返回链接成功,即客户端上线成功。
客户端上线成功后,即可以向服务端发送消息,服务端收到消息后,将消息转发给指定的客户端。一条聊天消息即发送成功。
一、 客户端主要依赖

客户端完成socket长连接功能,我选择的引用这个websocket包。

//websocket
    implementation 'org.java-websocket:Java-WebSocket:1.5.1'
//json解析    
    implementation 'com.google.code.gson:gson:2.7'

   

二、包引用完成后,创建wsClient类。

我的日志打印用了com.github.zhaokaiqiang.klog:library,所以是KLog方法打印

public class WsClient extends WebSocketClient {
    public WsClient(URI serverUri) {
        super(serverUri,new Draft_6455());
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        KLog.d("JWebSocketClient", "onOpen()");
    }

    @Override
    public void onMessage(String message) {
        KLog.d("JWebSocketClient", "onMessage()");
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        KLog.d("JWebSocketClient", "onClose()");
    }

    @Override
    public void onError(Exception ex) {
        KLog.d( "onError()"+ex);
    }
}

   

在业务逻辑中,调用WsClient(uri)(一般选择在用户登录成功后),开始调用这个方法完成长链接初始化,然后调用connectBlocking()开始尝试连接。

WsClient client = new WsClient(uri) {
            @Override
            public void onMessage(String message) {
                \\在这里处理服务端发来的消息
                KLog.d("onMessage", message);
            }
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                super.onOpen(handshakedata);
                KLog.i("SocketClientService", "websocket连接成功");
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                KLog.i("SocketClient", "onClose()");
            }
}

client.connectBlocking();

    
 

三、连接成功后,就可以在对于业务逻辑调用以下方法开始发送消息

public void sendMsg(String msg) {
        if (null != client) {
            try {
                client.send(msg);
            }catch (WebsocketNotConnectedException e){
                KLog.e("长连接发送失败", String.valueOf(e));
            }
            KLog.d("发送的消息", msg);
        }
    }

   

服务端实现会在下一章节更新

Create an account or sign in to comment

Recently Browsing 0

  • No registered users viewing this page.