在Android中使用 WebSocket 
 
WebSocket 是一种 支持客户端和 服务器之间全双工通信的协议。在 Android 中, 您可以使用 Java-WebSocket 库实现 WebSocket 通信。以下是 在 Android 应用程序中设置 和使用 WebSocket 的步骤。  
添加依赖项和权限  
首先,在您的 构建中包含 Java-WebSocket 库。gradle 文件:  
- <span style="background-color: rgb(255, 255, 255);">implementation 'org.java-websocket:Java-WebSocket:1.5.2'</span>
 
  复制代码 
此外,请确保 已将 INTERNET权限 添加到 您的AndroidManifest。xml: 
 
- <uses-permission android:name="android.permission.INTERNET" />
 
  复制代码 
创建 WebSocket客户端类  
通过扩展 WebSocketClient 类 创建 自定义 WebSocket 客户端 。这允许您 处理 WebSocket 事件,例如 连接打开、接收消息和错误。  
 
- 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")
 
 -    }
 
 - }
 
  复制代码 
 
建立 连接和发送消息  
要 连接到 WebSocket 服务器并发送消息,请按照下列步骤作:  
 
这是一个 例子: - 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!")
 
 -    }
 
 - }
 
  复制代码 
要记住的要点  
连接成功建立后 ,将触发 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 
 
 |