服务端与客户端建立连接后:
第一:服务端建立后,与客户端进行bind,接受数据,接受数据完毕后,告知客户端传输结果;
第二:客户端向客户端发送数据,使用socket.shutdownOutput()告知服务端,数据传输完毕;
但是,当使用socket.shutdownOutput()后,再次读取服务端的返回信息时,报错“Exception in thread "main" java.io.IOException: 远程主机强迫关闭了一个现有的连接。”
代码如下
服务端:
public class MyServerNio {
public static void main(String[] args) throws IOException {
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(6666));
SocketChannel client = server.accept();//客户端通道
FileChannel fileChannel = FileChannel.open(Paths.get("C:\Users\ycpad\Desktop\English\AfricanPoorChildren_1.docx"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
ByteBuffer bb = ByteBuffer.allocate(1024);
System.out.println("开始接受客户端数据。。。");
while((client.read(bb))!=-1){
bb.flip();
fileChannel.write(bb);
bb.clear();
}
fileChannel.close();
//通知客户端:接受数据完毕
bb.put("服务端server接受完毕".getBytes());
bb.flip();
client.write(bb);
bb.clear();
}
}
客户端:
public static void main(String[] args) throws IOException {
SocketChannel client = SocketChannel.open(new InetSocketAddress("127.0.0.1",6666));
FileChannel fileChannel = new FileInputStream("C:\Users\ycpad\Desktop\English\AfricanPoorChildren.docx").getChannel();
ByteBuffer bb = ByteBuffer.allocate(1024);
int i = 0;
while ((i=fileChannel.read(bb))!=-1) {
bb.flip();
client.write(bb);
bb.clear();
}
//通知服务端,数据传输完毕
client.shutdownOutput();
//接受服务端传送过来的数据
int result ;
while ((result = client.read(bb))!=-1){
bb.flip();
System.out.println(new String(bb.array(),0,result));
bb.clear();
}
fileChannel.close();
}
}