我正在创建一个通过套接字发送对象的应用程序(群组聊天项目)。首先,AsynchTask启动一个服务器进程,继续使用objectinputstream监听端口10000。每当从主线程输入消息时,它就会被传递到另一个AsynchTask,这是一个客户端进程,它构建并对象并将其发送到其他进程Asynch服务器任务。它发送的端口不是10000.我在尝试发送对象时遇到阻塞问题。我已经读过需要首先调用objectoutputstream但是我只看到在相同端口上读写时所讨论的内容。有没有办法连续监听端口上的对象并仅在必要时写入对象?
private class ServerTask extends AsyncTask<ServerSocket, Void, Void> {
@Override
protected Void doInBackground(ServerSocket... sockets) {
ServerSocket serverSocket = sockets[0];
while (true) {
try (
Socket clientSocket = serverSocket.accept();
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(clientSocket.getInputStream()));
) {
Log.i("I got Here", "I'm open");
Object o = in.readObject();
.
.
.
in.close();
clientSocket.close();
和客户端任务
private class ClientTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... msgs) {
try {
int remotePort = 11108;
int i;
for(i = 0; i<5;i++){
Socket socket = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}),
remotePort);
String msgToSend = msgs[0];
counter = counter++;
GroupMessageRequest m = new GroupMessageRequest();
m.id = Float.parseFloat(counter +"."+msgs[1]);
m.message = msgToSend;
m.sender = msgs[1];
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
out.flush();
out.writeObject(m);
out.close();
socket.close();
Log.e("Sent Message", "sent Message network");
remotePort = remotePort + 4;
}
} catch (UnknownHostException e) {
Log.e(TAG, "ClientTask UnknownHostException");
} catch (IOException e) {
Log.e(TAG, "ClientTask socket IOException");
}
return null;
}
}
套接字设置很奇怪,因为“hack”被用来让5个仿真器按照我需要的方式进行测试。我知道套接字不是问题,我不能让这些对象流做我想做的事情。非常感谢任何帮助!