android wifitcp连接传输代码
时间: 2024-01-07 08:04:52 浏览: 32
这是一个简单的Android WiFi TCP连接传输代码示例:
```
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.os.AsyncTask;
import android.util.Log;
public class WifiTcpClient extends AsyncTask<Void, Void, Void> {
private static final String TAG = "WifiTcpClient";
private String mIp;
private int mPort;
private String mMessage;
private Socket mSocket;
private OutputStream mOutput;
private InputStream mInput;
public WifiTcpClient(String ip, int port, String message) {
mIp = ip;
mPort = port;
mMessage = message;
}
@Override
protected Void doInBackground(Void... params) {
try {
mSocket = new Socket(mIp, mPort);
mOutput = mSocket.getOutputStream();
mInput = mSocket.getInputStream();
mOutput.write(mMessage.getBytes());
mOutput.flush();
Log.d(TAG, "Message sent: " + mMessage);
byte[] buffer = new byte[1024];
int len = mInput.read(buffer);
String response = new String(buffer, 0, len);
Log.d(TAG, "Response received: " + response);
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} finally {
try {
if (mOutput != null) {
mOutput.close();
}
if (mInput != null) {
mInput.close();
}
if (mSocket != null) {
mSocket.close();
}
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
```
这个类可以通过调用`execute()`方法来启动异步任务。在`doInBackground()`方法中,建立TCP连接并通过输出流发送消息。然后,从输入流中读取响应并打印到日志中。最后,关闭连接和流。在`onPostExecute()`方法中,可以执行异步任务完成后的操作。
使用示例:
```
new WifiTcpClient("192.168.1.100", 1234, "Hello, world!").execute();
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)