在Android中,使用Socket通信主要包括服务器端和客户端的实现。这里将分别介绍服务器端和客户端的实现过程。
服务器端实现:
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
String data = new String(buffer, 0, bytesRead);
// 处理客户端发送的数据
}
String response = "Hello from server!";
outputStream.write(response.getBytes());
outputStream.flush();
inputStream.close();
outputStream.close();
socket.close();
serverSocket.close();
客户端实现:
Socket socket = new Socket(serverAddress, port);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
String message = "Hello from client!";
outputStream.write(message.getBytes());
outputStream.flush();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
String data = new String(buffer, 0, bytesRead);
// 处理服务器发送的数据
}
inputStream.close();
outputStream.close();
socket.close();
以上就是Android中Socket通信的基本实现过程。注意在实际开发中,需要处理异常情况,例如网络异常、连接超时等。同时,为了提高程序的健壮性,建议在主线程之外执行网络操作,以避免阻塞主线程。可以使用异步任务(如AsyncTask
)或线程池(如ExecutorService
)来实现。