请创建 android websocket 代码
时间: 2024-05-03 12:22:45 浏览: 149
android web socket
以下是一个简单的Android WebSocket示例:
首先,在Android项目中添加以下依赖项:
```
implementation 'org.java-websocket:Java-WebSocket:1.4.0'
```
然后,创建一个WebSocket客户端类:
```
public class WebSocketClient extends Thread {
private final URI uri;
private WebSocket mWebSocket;
private boolean isConnected = false;
public WebSocketClient(String url) throws URISyntaxException {
uri = new URI(url);
}
@Override
public void run() {
super.run();
connectWebSocket();
}
private void connectWebSocket() {
WebSocketFactory factory = new WebSocketFactory();
try {
mWebSocket = factory.createSocket(uri);
} catch (IOException e) {
e.printStackTrace();
}
mWebSocket.addListener(new WebSocketAdapter() {
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
super.onConnected(websocket, headers);
isConnected = true;
Log.d("WebSocket", "Connected to server");
}
@Override
public void onTextMessage(WebSocket websocket, String message) throws Exception {
super.onTextMessage(websocket, message);
Log.d("WebSocket", "Received message: " + message);
}
@Override
public void onClose(WebSocket websocket, int code, String reason, boolean remote) throws Exception {
super.onClose(websocket, code, reason, remote);
isConnected = false;
Log.d("WebSocket", "Disconnected from server");
}
});
try {
mWebSocket.connect();
} catch (WebSocketException e) {
e.printStackTrace();
}
}
public void sendMessage(String message) {
if (isConnected && mWebSocket.isOpen()) {
mWebSocket.sendText(message);
Log.d("WebSocket", "Sent message: " + message);
}
}
public void disconnect() {
if (isConnected && mWebSocket.isOpen()) {
mWebSocket.disconnect();
}
}
}
```
接下来,在Activity中使用WebSocketClient:
```
public class MainActivity extends AppCompatActivity {
private WebSocketClient mWebSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mWebSocketClient = new WebSocketClient("ws://echo.websocket.org");
mWebSocketClient.start();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Button sendButton = findViewById(R.id.send_button);
final EditText messageEditText = findViewById(R.id.message_edittext);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String message = messageEditText.getText().toString();
mWebSocketClient.sendMessage(message);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mWebSocketClient.disconnect();
}
}
```
在此示例中,我们使用了echo.websocket.org作为WebSocket服务器。您可以替换为自己的WebSocket服务器URL。sendMessage()方法用于向服务器发送消息。disconnect()方法用于断开WebSocket连接。
阅读全文