为什么在java套接字中,我们不能连续发送消息?
这是我的粗略计划。我有两个客户端一个服务器我想得到结果 测试1 测试2 ... ... 但它只给我测试1 我尝试在服务器中添加reply方法和receive方法。正如我在下面提到的,问题解决了。结果是 测试1 测试1 测试2 测试2 测试1 测试2 为什么我必须添加此回复方法 服务器: 客户:为什么在java套接字中,我们不能连续发送消息?,java,sockets,Java,Sockets,这是我的粗略计划。我有两个客户端一个服务器我想得到结果 测试1 测试2 ... ... 但它只给我测试1 我尝试在服务器中添加reply方法和receive方法。正如我在下面提到的,问题解决了。结果是 测试1 测试1 测试2 测试2 测试1 测试2 为什么我必须添加此回复方法 服务器: 客户: 使用ByteBuffer.array无效:您必须翻转缓冲区并从中获取,而不是像现在这样忽略其位置和限制。或者使用position和limit作为offset和length参数来构造ByteArrayOut
使用ByteBuffer.array无效:您必须翻转缓冲区并从中获取,而不是像现在这样忽略其位置和限制。或者使用position和limit作为offset和length参数来构造ByteArrayOutputStream。似乎我忘了放一些东西。我现在就加上,好吧,但你还是误用了ByteBuffer。
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
while ( keys.hasNext() ) {
SelectionKey key = (SelectionKey)keys.next();
keys.remove();
if (!key.isValid())
continue;
if (key.isReadable()) {
SocketChannel nsc = (SocketChannel) key.channel();
// clear buffer for reading
readBuffer.clear();
int nBytes = nsc.read(readBuffer);
DataInputStream ist = new DataInputStream (
new ByteArrayInputStream(readBuffer.array()));
String info = ist.readUTF();
switch (info) {
case TAKE:
System.out.println("Test1");
/*writeBuffer.clear();
writeBuffer.putInt(1);
writeBuffer.flip();
nsc.write(writeBuffer);*/ // the reply method
break;
case BUN:
System.out.println("Test2");
break;
}
}
}
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
DataInputStream in = new DataInputStream(sock.getInputStream());
do {
try {
out.writeUTF("TAKE ");
//in.readInt(); the receive method
out.writeUTF("BUN ");
Thread.sleep(id + 1);
} catch (IOException ioe) {
sock.close();
throw ioe;
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
} while (true);