package client;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;
public class NioClient {
public static void main(String[]args){
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketChannel socketChannel = null;
ByteBuffer res=ByteBuffer.allocate(1024);
try
{
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("localhost",8080));
if(socketChannel.finishConnect())
{
int i=0;
int size=0;
while(true)
{
TimeUnit.SECONDS.sleep(1);
String info = "I'm "+i+++"-th information from client";
buffer.clear();
buffer.put(info.getBytes());
buffer.flip();
while(buffer.hasRemaining()){
// System.out.println(buffer);
socketChannel.write(buffer);
}
size=socketChannel.read(res);
while((size)!=0){
res.flip();
byte result[]=new byte[size];
res.get(result);
System.out.println(new String(result));
res.clear();
}
}
}
}
catch (IOException | InterruptedException e)
{
e.printStackTrace();
}
finally{
try{
if(socketChannel!=null){
socketChannel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
解决方法:
将while循环上的赋值放到while循环里
while((size=socketChannel.read(res))!=0){
为什么会这样,求解释???
另附赠服务端代码
package client;
import java.io.*;
import java.net.*;
import message.IMessage;
import message.LoginMessage;
public class Server2 {
public static void main(String[] args) throws IOException {
Server2 socketService = new Server2();
socketService.oneServer();
}
public void oneServer() {
ServerSocket serverSocket = null;
InputStream in=null;
OutputStream out =null;
try
{
System.out.println(" server start");
serverSocket = new ServerSocket(8080);
int Size = 0;
byte[] res = new byte[1024];
while(true){
Socket clntSocket = serverSocket.accept();
SocketAddress clientAddress = clntSocket.getRemoteSocketAddress();
System.out.println("Handling client at "+clientAddress);
in = clntSocket.getInputStream();
out=clntSocket.getOutputStream();
int i=0;
while((Size=in.read(res))!=-1){
byte[] temp = new byte[Size];
System.arraycopy(res, 0, temp, 0, Size);
System.out.println(new String(temp));
String status="success"+i;
i++;
out.write(status.getBytes());
out.flush();
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
try{
if(serverSocket!=null){
serverSocket.close();
}
if(in!=null){
in.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
上面写的是读完了在读一遍,重新给size赋值,发现size=0,结束;
而
while((size)!=0)
size
是一个固定的值,你循环里面又没有重新赋值