Discuz! BBS

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 33|回复: 0

Using WebSocket in Android

[复制链接]

393

主题

556

帖子

3294

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
3294
发表于 6 天前 | 显示全部楼层 |阅读模式
在Android中使用 WebSocket

WebSocket 是一种 支持客户端和 服务器之间全双工通信的协议。在 Android 中, 您可以使用 Java-WebSocket 库实现 WebSocket 通信。以下是 在 Android 应用程序中设置 和使用 WebSocket 的步骤。


添加依赖项和权限


首先,在您的 构建中包含 Java-WebSocket 库。gradle 文件:


  1. <span style="background-color: rgb(255, 255, 255);">implementation 'org.java-websocket:Java-WebSocket:1.5.2'</span>
复制代码

此外,请确保 已将 INTERNET权限 添加到 您的AndroidManifest。xml

  1. <uses-permission android:name="android.permission.INTERNET" />
复制代码

创建 WebSocket客户端类


通过扩展 WebSocketClient 类 创建 自定义 WebSocket 客户端 。这允许您 处理 WebSocket 事件,例如 连接打开、接收消息和错误。



  1. import android.util.Log
  2. import org.java_websocket.client.WebSocketClient
  3. import org.java_websocket.handshake.ServerHandshake
  4. import java.net.URI
  5. open class MyWebSocketClient(serverUri: URI?) : WebSocketClient(serverUri) {
  6.    private val TAG = "MyWebSocketClient"
  7.    override fun onOpen(handshakedata: ServerHandshake?) {
  8.        Log.i(TAG, "Connection opened: $handshakedata")
  9.    }
  10.    override fun onMessage(message: String?) {
  11.        Log.i(TAG, "Message received: $message")
  12.    }
  13.    override fun onClose(code: Int, reason: String?, remote: Boolean) {
  14.        Log.i(TAG, "Connection closed: Code=$code, Reason=$reason, Remote=$remote")
  15.    }
  16.    override fun onError(ex: Exception?) {
  17.        Log.e(TAG, "Error occurred: $ex")
  18.    }
  19. }
复制代码


建立 连接和发送消息


要 连接到 WebSocket 服务器并发送消息,请按照下列步骤作:


  • 创建 自定义 MyWebSocketClient 类的实例。

  • 使用 connectBlocking() 方法建立 连接。

  • 使用 send() 方法向服务器发送消息 。



这是一个 例子:

  1. import androidx.appcompat.app.AppCompatActivity
  2. import android.os.Bundle
  3. import java.net.URI
  4. class MainActivity : AppCompatActivity() {
  5.    override fun onCreate(savedInstanceState: Bundle?) {
  6.        super.onCreate(savedInstanceState)
  7.        setContentView(R.layout.activity_main)
  8.        // WebSocket server URI
  9.        val uri: URI = URI.create("ws://your-server-address")
  10.        // Create WebSocket client instance
  11.        val client = object : MyWebSocketClient(uri) {
  12.            override fun onMessage(message: String?) {
  13.                super.onMessage(message)
  14.                // Handle received messages here
  15.            }
  16.        }
  17.        // Connect to the server
  18.        client.connectBlocking()
  19.        // Send a message to the server
  20.        client.send("Hello, WebSocket!")
  21.    }
  22. }
复制代码

要记住的要点


  • 连接成功建立后 ,将触发 onOpen 方法。

  • 来自 服务器的消息 在 onMessage 方法中处理。

  • 使用 onClose 处理 连接关闭, 使用 onError 管理 错误。

  • 始终确保 WebSocket 服务器 URI 正确 且可访问。



此设置提供了一种在 Android 应用程序中实现 WebSocket 通信的强大方法,从而实现与服务器的实时数据交换。


ref:【Android WebSocket】Android 端 WebSocket 基本用法 ( 添加依赖和权限 | 创建 WebSocketClient 客户端类 | 建立连接并发送消息 )-腾讯云开发者社区-腾讯云




WebSocket is a protocol that enables full-duplex communication between a client and a server. In Android, you can implement WebSocket communication using the Java-WebSocket library. Below are the steps to set up and use WebSocket in an Android application.

Adding Dependencies and Permissions

To begin, include the Java-WebSocket library in your build.gradle file:

implementation 'org.java-websocket:Java-WebSocket:1.5.2'
Copy
Also, ensure that the INTERNET permission is added to your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
Copy
Creating a WebSocket Client Class

Create a custom WebSocket client by extending the WebSocketClient class. This allows you to handle WebSocket events such as connection opening, receiving messages, and errors.

import android.util.Log
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.net.URI

open class MyWebSocketClient(serverUri: URI?) : WebSocketClient(serverUri) {
private val TAG = "MyWebSocketClient"

override fun onOpen(handshakedata: ServerHandshake?) {
Log.i(TAG, "Connection opened: $handshakedata")
}

override fun onMessage(message: String?) {
Log.i(TAG, "Message received: $message")
}

override fun onClose(code: Int, reason: String?, remote: Boolean) {
Log.i(TAG, "Connection closed: Code=$code, Reason=$reason, Remote=$remote")
}

override fun onError(ex: Exception?) {
Log.e(TAG, "Error occurred: $ex")
}
}
Copy
Establishing a Connection and Sending Messages

To connect to a WebSocket server and send messages, follow these steps:

Create an instance of your custom MyWebSocketClient class.

Use the connectBlocking() method to establish a connection.

Use the send() method to send messages to the server.

Here’s an example:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import java.net.URI

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// WebSocket server URI
val uri: URI = URI.create("ws://your-server-address")

// Create WebSocket client instance
val client = object : MyWebSocketClient(uri) {
override fun onMessage(message: String?) {
super.onMessage(message)
// Handle received messages here
}
}

// Connect to the server
client.connectBlocking()

// Send a message to the server
client.send("Hello, WebSocket!")
}
}
Copy
Key Points to Remember

The onOpen method is triggered when the connection is successfully established.

Messages from the server are handled in the onMessage method.

Use onClose to handle connection closures and onError to manage errors.

Always ensure the WebSocket server URI is correct and accessible.

This setup provides a robust way to implement WebSocket communication in Android applications, enabling real-time data exchange with servers.

Learn more:
1 -
cloud.tencent.com

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|DiscuzX

GMT+8, 2025-10-25 08:51 , Processed in 0.011817 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表