要使用Android Studio创建一个基于Java的WebSocket客户端和服务器,可以按照以下步骤进行操作:
app
模块下的build.gradle
文件中添加以下依赖项:implementation 'org.java-websocket:Java-WebSocket:1.5.1'
MainActivity.java
文件中添加以下代码来实现WebSocket客户端:import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
WebSocketClient mWebSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectWebSocket();
}
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://your_server_url");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("WebSocket", "Opened");
mWebSocketClient.send("Hello, Server!");
}
@Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
// 处理接收到的消息
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("WebSocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("WebSocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
}
WebSocketServer.java
,并添加以下代码:import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.net.InetSocketAddress;
public class WebSocketServerExample extends WebSocketServer {
public WebSocketServerExample(int port) {
super(new InetSocketAddress(port));
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
conn.send("Welcome to the server!");
broadcast("new connection: " + handshake.getResourceDescriptor());
System.out.println("new connection to " + conn.getRemoteSocketAddress());
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
System.out.println("closed " + conn.getRemoteSocketAddress() + " with exit code " + code + " additional info: " + reason);
}
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("received message from " + conn.getRemoteSocketAddress() + ": " + message);
}
@Override
public void onError(WebSocket conn, Exception ex) {
System.err.println("an error occurred on connection " + conn.getRemoteSocketAddress() + ":" + ex);
}
public static void main(String[] args) {
int port = 8887; // 端口号
WebSocketServerExample server = new WebSocketServerExample(port);
server.start();
System.out.println("WebSocket server started on port: " + server.getPort());
}
}
请注意,这只是一个简单的示例,你可以根据你的需求进行相应的更改和扩展。
这样,你就可以使用Android Studio创建一个基于Java的WebSocket客户端和服务器了。