客户端和服务器端Channel写法:阻塞和非阻塞

1.客户端:;

//阻塞式的客户端
public class Test05 {
public static void main(String[] args) throws IOException {
//1.创建SocketChannel
SocketChannel socketChannel = SocketChannel.open();
//2.去连接服务器
boolean b = socketChannel.connect(new InetSocketAddress(“192.168.3.54”, 6666));
//相当于之前连接的客户端代码 : Socket socket = new Socket(“192.168.3.54”,6666);
//3.后续代码
System.out.println(“后续代码…”);
}
}
//非阻塞客户端
public class Test06 {
public static void main(String[] args) throws IOException {
//1.创建SocketChannel对象
SocketChannel socketChannel = SocketChannel.open();
//设置:设置为非阻塞
socketChannel.configureBlocking(false);
while (true){
//2.去连接服务器
try{
boolean b = socketChannel.connect(new InetSocketAddress(“192.1668.3.54”, 6666));
//相当于之前TCP客户端连接服务端的代码:Socket socket = new Socket(“192.168.3.54”,6666);
//3.后续代码
System.out.println(“后续代码…”);
//4.判断
if(b){
System.out.println(“和服务器进行交互…”);
}
}catch (Exception e){
System.out.println(“4秒后重新连接…”);
try {
Thread.sleep(4000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
}

2.服务器端:

//创建阻塞的服务器通道
public class Test03 {
public static void main(String[] args) throws IOException {
//1.创建ServerSocketChannel
ServerSocketChannel server = ServerSocketChannel.open();
//2.绑定本地的某大端口
server.bind(new InetSocketAddress(6666));
System.out.println(“服务器已经启动…”);
//3.接收客户端通道
SocketChannel socketChannel = server.accept();
//4.后续代码
System.out.println(“后续代码…”);
}
}

//同步非阻塞的服务通道…
public class Test04 {
public static void main(String[] args) throws IOException {
//1.创建ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//2.设置为同步非阻塞的服务器通道
serverSocketChannel.configureBlocking(false);
//3.绑定本地的某个端口
serverSocketChannel.bind(new InetSocketAddress(6666));
System.out.println(“服务器启动了…”);
while (true){
//4.接收客户端通道
SocketChannel socketChannel = serverSocketChannel.accept();
//5.后续代码
System.out.println(“后续代码…”);
if(socketChannel!=null){
System.out.println(“和客户端进行交互…”);
}else {
System.out.println(“暂时没有客户端,4秒后继续查看…”);
try {
Thread.sleep(4000); //模拟服务器去做其他任务
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}

你可能感兴趣的:(笔记)