public class Client { public static void main(String[] args) throws Exception{ client(); }
public static void client()throws Exception{
//1获取网络通道
SocketChannel socket= SocketChannel.open(new InetSocketAddress("127.0.0.1",8096));
//3 获取本地的文件通道
FileChannel fileChannel=FileChannel.open(Paths.get("d:/test/aa.txt"), StandardOpenOption.READ);
//2 获取缓冲区
ByteBuffer buf=ByteBuffer.allocate(1024);
//4 读取本地文件,发送到服务器
while (fileChannel.read(buf)!=-1){
buf.flip();
socket.write(buf);
buf.clear();
}
//5 关闭通道
fileChannel.close();
socket.close();
} }
public class Server {
public static void main(String[] args)throws Exception {
server();
}
public static void server()throws Exception{
//1 建立网络通道 ,这个是静态方法,打开服务器端套接字通道
ServerSocketChannel socketChannel =ServerSocketChannel.open();
//4 获取本地文件通道
FileChannel fileChannel=FileChannel.open(
Paths.get("d:/test/a_a_a.txt"),
StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//2 绑定连接 InetSocketAddresss是SocketAddress(是个抽象类)的子类
socketChannel.bind(new InetSocketAddress(8096));
//3接受到此通道套接字的连接。 接受客户端连接的通道,要用套接字通道来接收
SocketChannel sclient = socketChannel.accept();
//4建立缓冲区
ByteBuffer buffer=ByteBuffer.allocate(1024);
while (sclient.read(buffer)!=-1){
buffer.flip();
fileChannel.write(buffer);
buffer.clear();
}
fileChannel.close();
sclient.close();
socketChannel.close();
} }
//下面的是有交互的,还是阻塞式的
public class Client1 { public static void main(String[] args) throws Exception{ client(); } public static void client() throws Exception{
//1建立网络套接字通过
SocketChannel socketChannel =SocketChannel.open(new InetSocketAddress("127.0.0.1",8989));
//2获取文件传输通道
FileChannel fileChannel =FileChannel.open(Paths.get("d:/test/3.xml"),StandardOpenOption.READ);
//3获取缓冲区
ByteBuffer buffer=ByteBuffer.allocate(1024);
//4进行文件传输
while (fileChannel.read(buffer)!=-1){
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
}
//关闭向外写出的流
socketChannel.shutdownOutput();
//5接收服务器端的信息
while (socketChannel.read(buffer)!=-1){
buffer.flip();
System.out.println(new String(buffer.array(),0,buffer.limit()));
buffer.clear();
}
//6关闭通道
socketChannel.close();
fileChannel.close();
}
} public class Server1 {
public static void main(String[] args) throws Exception{
server();
}
public static void server()throws Exception{
//1打开服务器端套接字通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//2 绑定连接
serverSocketChannel.bind(new InetSocketAddress(8989));
//3接受套接字通信通道
SocketChannel socketChannel=serverSocketChannel.accept();
//4 打开本地文件通道
FileChannel fileChannel = FileChannel.open(Paths.get("d:/test/3_copy_copy.xml"),
StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//5建立个缓冲器
ByteBuffer buffer =ByteBuffer.allocate(1024);
//6将内容写入到本地中
while (socketChannel.read(buffer)!=-1){
buffer.flip();
fileChannel.write(buffer);
buffer.clear();
}
//7给客户端回条消息
buffer.put("消息收到了".getBytes());
buffer.flip();
socketChannel.write(buffer);
//8关闭通道
socketChannel.close();
serverSocketChannel.close();
fileChannel.close();
}
}