okhttp android socket 发送sendmessage消息
时间: 2023-11-13 08:06:21 浏览: 93
android okhttp
5星 · 资源好评率100%
要使用 OkHttp 在 Android 应用中发送 Socket 消息,可以按照以下步骤:
1. 添加 OkHttp 依赖
在 app 的 build.gradle 文件中添加 OkHttp 依赖:
```groovy
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
}
```
2. 创建 OkHttpClient 对象
```java
OkHttpClient client = new OkHttpClient();
```
3. 创建 Socket 连接
```java
Socket socket = new Socket("your_server_ip_address", your_server_port_number);
```
4. 获取 Socket 的输入输出流
```java
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
```
5. 向服务器发送消息
```java
String message = "your_message";
outputStream.write(message.getBytes());
```
6. 接收服务器返回的消息
```java
byte[] response = new byte[1024];
int length = inputStream.read(response);
String responseString = new String(response, 0, length);
```
7. 关闭连接和流
```java
outputStream.close();
inputStream.close();
socket.close();
```
完整的示例代码如下:
```java
OkHttpClient client = new OkHttpClient();
try {
Socket socket = new Socket("your_server_ip_address", your_server_port_number);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
String message = "your_message";
outputStream.write(message.getBytes());
byte[] response = new byte[1024];
int length = inputStream.read(response);
String responseString = new String(response, 0, length);
outputStream.close();
inputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
```
阅读全文