【发布时间】:2020-12-14 21:06:17
【问题描述】:
我为客户端创建了套接字编程类。已建立连接。服务器向客户端发送消息。客户端可以从服务器获取消息。但客户端只发送一个答案。为什么?输出流错了吗?
public class Message extends AsyncTask<byte[], Void, Void> {
Socket s;
public static byte[] recv;
@Override
protected Void doInBackground(byte[]... voids) {
byte[] message = voids[0];
try {
s = new Socket(destIp, destPort);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeInt(message.length);
dos.write(message);
dos.flush();
InputStream inFromServer = s.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
byte[] buffer = new byte[200];
int read = 0;
while ((read = in.read(buffer, 0, buffer.length)) != -1) {
// in.read(buffer);
recv = Arrays.copyOf(buffer, read);
Context context = getContext();
Intent intentManager = new Intent(context, ManagerService.class);
context.startService(intentManager);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
【问题讨论】:
-
Connection was made. Server send a message to client.可以。您没有发布服务器代码,所以我们不得不认为这是理所当然的。但是我们看到了您的客户端代码。客户端也在连接时发送消息。那是一个错误的协议。决定两者中的哪一个先发送消息。然后另一个必须先阅读消息。 -
因为,你有输出流写入功能。然后客户端将只发送一次消息。如果您希望客户端继续发送消息并从服务器读回,请尝试在循环中相应地包括写入和读取。
-
无法检查是否会在循环中发送回复@Liju
标签: android sockets client outputstream