android socket客户端和服务端通信
时间: 2023-10-01 07:03:41 浏览: 173
在 Android 上实现 Socket 客户端和服务端通信,可以通过 Java 的 Socket 编程实现。下面是一个简单的示例:
1. 服务端代码:
```java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接:" + socket.getInetAddress());
Thread thread = new Thread(new ServerThread(socket));
thread.start();
}
}
}
```
2. 服务端线程代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ServerThread implements Runnable {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str = reader.readLine()) != null) {
System.out.println("客户端发送消息:" + str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
3. 客户端代码:
```java
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 8888);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("Hello Server".getBytes());
outputStream.flush();
socket.shutdownOutput();
socket.close();
}
}
```
在服务端启动后,等待客户端连接,当客户端连接后,开启一个线程处理客户端的请求。客户端通过 Socket 连接到服务端,发送消息后关闭连接。
注意:以上代码仅为示例,没有进行异常处理等操作,实际使用时需要根据具体需求补充完整。
阅读全文