Android异步TCP通信可以通过使用Java的Socket和ServerSocket类来实现。以下是一些示例代码:
- 建立TCP服务器
public class TCPServer implements Runnable {
ServerSocket serverSocket;
public TCPServer() throws IOException {
serverSocket = new ServerSocket(8080);
}
@Override
public void run() {
while (true) {
try {
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = reader.readLine();
System.out.println("Received message: " + message);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
writer.println("Response from server");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 建立TCP客户端
public class TCPClient {
private final String serverAddress;
private final int serverPort;
public TCPClient(String address, int port) {
this.serverAddress = address;
this.serverPort = port;
}
public void sendMessage(final String message) {
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
Socket socket = new Socket(serverAddress, serverPort);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
writer.println(message);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = reader.readLine();
System.out.println("Received response: " + response);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
- 在activity中使用客户端发送消息
public class MainActivity extends AppCompatActivity {
TCPClient tcpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tcpClient = new TCPClient("localhost", 8080);
}
public void onSendMessageClick(View v) {
String message = ((EditText) findViewById(R.id.messageEditText)).getText().toString();
tcpClient.sendMessage(message);
}
}
这里使用了AsyncTask来进行异步通信,以避免阻塞UI线程。注意,在实际开发中,还需要处理网络连接超时等异常情况。
Android 异步 TCP 通信可以通过使用 Socket 和 Handler 来实现。以下是一些基本的步骤:
- 创建一个 Socket 实例,并设置连接超时时间和读取超时时间。
- 在主线程中创建一个 Handler 实例,用于在接收到来自网络的响应时更新 UI 线程。
- 在另一个线程中创建一个 TCP 客户端,连接到服务器并发送请求数据。
- 通过输入流从服务器接收响应数据,并将数据发送到主线程中的 Handler 实例。
- 在 Handler 实例中更新 UI 线程。
以下是一个示例代码:
private static final String SERVER_IP = "127.0.0.1";
private static final int SERVER_PORT = 9000;
private static final int CONNECTION_TIMEOUT = 5000;
private static final int READ_TIMEOUT = 5000;
// 创建 Socket 实例
Socket socket = new Socket();
socket.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT), CONNECTION_TIMEOUT);
socket.setSoTimeout(READ_TIMEOUT);
// 在主线程创建 Handler 实例
Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
// 在 UI 线程中更新界面
// ...
}
};
// 在另一个线程中进行 TCP 客户端通信
Thread tcpThread = new Thread(new Runnable() {
@Override
public void run() {
try {
// 发送请求数据
OutputStream os = socket.getOutputStream();
os.write("request data".getBytes());
os.flush();
// 接收响应数据
InputStream is = socket.getInputStream();
byte[] buffer = new byte[1024];
int length = is.read(buffer);
String response = new String(buffer, 0, length);
// 将响应数据发送到主线程中的 Handler 实例
Message msg = handler.obtainMessage();
msg.obj = response;
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
tcpThread.start();
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/158537.html