AndroidTCP详细demo
时间: 2023-09-15 20:16:43 浏览: 91
android TCP demo
这里是一个简单的 Android TCP 客户端和服务器的详细 demo。
1. 创建一个新的 Android 项目,并在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
```
2. 在 MainActivity.java 文件中创建两个类:ServerThread 和 ClientThread,分别用于启动 TCP 服务器和客户端。
```java
public class ServerThread extends Thread {
private ServerSocket serverSocket;
@Override
public void run() {
try {
serverSocket = new ServerSocket(8888);
while (true) {
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = in.readLine();
Log.d("ServerThread", "Received message: " + message);
in.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientThread extends Thread {
private String ip;
private int port;
private String message;
public ClientThread(String ip, int port, String message) {
this.ip = ip;
this.port = port;
this.message = message;
}
@Override
public void run() {
try {
Socket socket = new Socket(ip, port);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(message);
out.flush();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
3. 在 MainActivity 的 onCreate() 方法中启动 TCP 服务器和客户端:
```java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Start server thread
ServerThread serverThread = new ServerThread();
serverThread.start();
// Start client thread
ClientThread clientThread = new ClientThread("localhost", 8888, "Hello, server!");
clientThread.start();
}
```
4. 运行应用程序,并在 Logcat 中查看输出:
```
D/ServerThread: Received message: Hello, server!
```
这就是一个简单的 Android TCP 客户端和服务器的详细 demo。你可以根据自己的需要进行修改和扩展。
阅读全文