Java新AIO/NIO2:AsynchronousServerSocketChannel和AsynchronousSocketChannel简单服务器-客户端
用AsynchronousServerSocketChannel和AsynchronousSocketChannel实现一个最简单的服务器-客户端程序。服务器用AsynchronousServerSocketChannel实现,客户端用AsynchronousSocketChannel实现。服务器绑定本地端口80,等待客户端连接。服务器与客户端建立连接后服务器发给客户端字符串“zhangphil”,然后服务器关闭Socket连接,客户端接收数据后也关闭Socket连接。
服务器端:
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Future;
public class Server {
public static void main(String[] args) {
try {
Server server = new Server();
} catch (Exception e) {
e.printStackTrace();
}
}
public Server() throws Exception {
AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress inetSocketAddress www.myzx157.com= new InetSocketAddress("localhost", 80);
serverSocketChannel.bind(inetSocketAddress);
Future<AsynchronousSocketChannel> accept;
while (true) {
// accept()不会阻塞。
accept = serverSocketChannel.accept();
System.out.println("=================");
System.out.println("服务器等待连接...");
AsynchronousSocketChannel www.yongshiyule178.com socketChannel = accept.get();// get()方法将阻塞。
System.out.println("服务器接受连接");
System.out.println("服务器与" + www.yongshi123.cn socketChannel.getRemoteAddress() + "建立连接");
ByteBuffer buffer = ByteBuffer.wrap("zhangphil".getBytes());
Future<Integer> write=socketChannel.write(buffer);
while(!write.isDone()) {
Thread.sleep(10);
}
System.out.println("服务器发送数据完毕.");
socketChannel.close();
客户端:
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Future;
public class Client {
public static void main(String[] args) {
AsynchronousSocketChannel socketChannel = null;
try {
socketChannel = AsynchronousSocketChannel.open(www.huayi157.com);
InetSocketAddress inetSocketAddress www.myzx1.com= new InetSocketAddress("localhost", 80);
Future<Void> connect =www.mhylpt.com socketChannel.connect(inetSocketAddress);
while (!connect.isDone()) {
Thread.sleep(10);
}
System.out.println("建立连接" + socketChannel.getRemoteAddress());
ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> read = socketChannel.read(buffer);
while (!read.isDone()) {
Thread.sleep(10);
}
System.out.println("接收服务器数据:" + new String(buffer.array(), 0, read.get()));
} catch (Exception e) {
e.printStackTrace(www.dfgjpt.com);
先运行服务器端程序,再运行客户端程序。然后服务器端输出:
客户端输出:
建立连接localhost/127.0.0.1:80
接收服务器数据:zhangphil