废话不多说直接上代码
首选导入
implementation "org.java-websocket:Java-WebSocket:1.4.0"
java
package com.zx.qnncpds.androidwbsocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import com.zx.qnncpds.androidwbsocket.client.ClientActivity;
import com.zx.qnncpds.androidwbsocket.service.ServiceActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1://客户端
startActivity(new Intent(MainActivity.this, ClientActivity.class));
break;
case R.id.btn2://服务端
startActivity(new Intent(MainActivity.this, ServiceActivity.class));
break;
default:
break;
}
}
}
布局
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="客服端" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="服务端" />
</LinearLayout>
客服端
java
package com.zx.qnncpds.androidwbsocket.client;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.zx.qnncpds.androidwbsocket.R;
import java.net.URI;
import java.net.URISyntaxException;
public class ClientActivity extends AppCompatActivity implements ClientWebSocketListener {
private WebSocketClient webSocketClient;
private Button btn_send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
btn_send=findViewById(R.id.btn_send);
btn_send.setOnClickListener(v -> sendMessage("测试消息"));
try {
// 替换为你的WebSocket服务器URI
URI uri = new URI("ws://10.10.10.104:9007");
webSocketClient = new WebSocketClient(uri, this);
webSocketClient.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
/**
* @param message 当WebSocket接收到消息时调用此方法
*/
@Override
public void onMessage(final String message) {
}
/**
* @param message 连接打开
*/
@Override
public void onOpen(String message) {
}
/**
* @param message 连接关闭
*/
@Override
public void onClose(String message) {
}
/**
* @param message 出现错误
*/
@Override
public void onError(String message) {
}
public void sendMessage(String message) {
// 发送一个消息到WebSocket服务器
if (webSocketClient != null && webSocketClient.isOpen()) {
webSocketClient.send(message);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 关闭WebSocket连接以避免内存泄露
if (webSocketClient != null) {
webSocketClient.close();
}
}
}
java
package com.zx.qnncpds.androidwbsocket.client;
public interface ClientWebSocketListener {
/**
* @param message 当WebSocket接收到消息时调用此方法
*/
void onMessage(final String message);
/**
* @param message 连接打开
*/
void onOpen(final String message);
/**
* @param message 连接关闭
*/
void onClose(final String message);
/**
* @param message 出现错误
*/
void onError(final String message);
}
java
package com.zx.qnncpds.androidwbsocket.client;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
public class WebSocketClient extends org.java_websocket.client.WebSocketClient {
private ClientWebSocketListener webSocketListener;
public WebSocketClient(URI serverUri, ClientWebSocketListener listener) {
super(serverUri);
this.webSocketListener = listener;
}
@Override
public void onOpen(ServerHandshake handshakeData) {
System.out.println("WebSocket 连接打开");
if (webSocketListener != null) {
webSocketListener.onOpen("WebSocket 连接打开");
}
}
@Override
public void onMessage(String message) {
if (webSocketListener != null) {
webSocketListener.onMessage(message);
}
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("WebSocket 连接关闭");
if (webSocketListener != null) {
webSocketListener.onClose("WebSocket 连接关闭");
}
}
@Override
public void onError(Exception ex) {
System.out.println("WebSocket 出现错误: " + ex.getMessage());
if (webSocketListener != null) {
webSocketListener.onError("WebSocket 出现错误: " + ex.getMessage());
}
}
}
服务端
java
package com.zx.qnncpds.androidwbsocket.service;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.zx.qnncpds.androidwbsocket.R;
import org.java_websocket.WebSocket;
import java.io.IOException;
public class ServiceActivity extends Activity implements ServiceWebSocketListener {
// WebSocket服务器的实例
private AndroidWebSocketServer server;
private TextView tv_state;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
tv_state=findViewById(R.id.tv_state);
// 创建并启动WebSocket服务器
server = new AndroidWebSocketServer(8887, this);
server.start();
}
@Override
public void onClientOpen(WebSocket conn, String address) {
runOnUiThread(() -> {
// 更新UI显示连接的客户端的地址
// 例如:更新一个文本视图来显示已连接
tv_state.setText(address);
});
}
@Override
public void onClientClose(WebSocket conn, int code, String reason, boolean remote) {
runOnUiThread(() -> {
// 更新UI以表示客户端断开连接
// 例如:更新列表视图中的项目
tv_state.setText("客户端以断开");
});
}
@Override
public void onClientMessage(WebSocket conn, String message) {
runOnUiThread(() -> {
// 在UI上展示收到的消息
// 例如:将消息添加到聊天窗口
tv_state.setText(message);
});
}
@Override
public void onClientError(WebSocket conn, Exception ex) {
runOnUiThread(() -> {
// 在UI上展示错误信息
// 例如:展示一个错误弹窗
});
}
@Override
public void onServerStart() {
runOnUiThread(() -> {
// 更新UI表示服务器已经启动
// 例如:改变一个文本视图的文本
tv_state.setText("服务器已启动");
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (server != null) {
try {
server.stop();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}
// 广播消息给所有WebSocket客户端
public void broadcastToAll(String message) {
server.broadcastMessage(message);
}
// 发送消息给特定的WebSocket客户端
public void sendToClient(WebSocket client, String message) {
server.sendMessageToClient(client, message);
}
}
java
package com.zx.qnncpds.androidwbsocket.service;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.net.InetSocketAddress;
public class AndroidWebSocketServer extends WebSocketServer {
// 事件监听器,用于将事件通知给ServiceActivity
private ServiceWebSocketListener serviceWebSocketListener;
/**
* 构造函数。
* @param port 服务器侦听的端口号。
* @param serviceWebSocketListener 事件发生时的回调监听器。
*/
public AndroidWebSocketServer(int port, ServiceWebSocketListener serviceWebSocketListener) {
super(new InetSocketAddress(port));
this.serviceWebSocketListener = serviceWebSocketListener;
}
public AndroidWebSocketServer(int port) {
super(new InetSocketAddress(port));
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
// 客户端连接打开时调用监听器的onClientOpen方法
String address = conn.getRemoteSocketAddress().getAddress().getHostAddress();
serviceWebSocketListener.onClientOpen(conn, address);
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
// 客户端连接关闭时调用监听器的onClientClose方法
String address = conn.getRemoteSocketAddress().getAddress().getHostAddress();
serviceWebSocketListener.onClientClose(conn, code, reason, remote);
}
@Override
public void onMessage(WebSocket conn, String message) {
// 接收到客户端消息时调用监听器的onClientMessage方法
serviceWebSocketListener.onClientMessage(conn, message);
}
@Override
public void onError(WebSocket conn, Exception ex) {
// 连接发生错误时调用监听器的onClientError方法
serviceWebSocketListener.onClientError(conn, ex);
}
@Override
public void onStart() {
// WebSocket服务器启动时调用监听器的onServerStart方法
serviceWebSocketListener.onServerStart();
}
// 发送消息到所有连接的WebSocket客户端
public void broadcastMessage(String message) {
broadcast(message);
}
// 发送消息到特定的WebSocket客户端
public void sendMessageToClient(WebSocket conn, String message) {
if (conn != null) {
conn.send(message);
}
}
}
java
package com.zx.qnncpds.androidwbsocket.service;
import org.java_websocket.WebSocket;
public interface ServiceWebSocketListener {
/**当客户端连接打开时调用
* @param conn
* @param address
*/
void onClientOpen(WebSocket conn, String address);
// 当客户端连接关闭时调用
/** 当客户端连接关闭时调用
* @param conn
* @param code
* @param reason
* @param remote
*/
void onClientClose(WebSocket conn, int code, String reason, boolean remote);
/**当接收到客户端消息时调用
* @param conn
* @param message
*/
void onClientMessage(WebSocket conn, String message);
/**
* 当客户端连接发生错误时调用
* @param conn
* @param ex
*/
void onClientError(WebSocket conn, Exception ex);
/**
*当WebSocket服务器启动时调用
*/
void onServerStart();
}
布局加一个文本这就不写了(服务端和客服端都一样)
项目案例 https://download.csdn.net/download/qq_41733851/88885469?spm=1001.2014.3001.5503