客户端服务端轮询通信
服务端建立
try {
//建立服务端
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8099));
//创建轮询器
Selector selector = Selector.open();
//把当前的服务端serversocketchannel注册到轮询器上
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
boolean isStop = true;
while (isStop){
//此处需要对selector进行引用操作,不能写在循环外面
int countKey = selector.select();
//判断服务端是否正常开启
if (serverSocketChannel.isOpen()){
//获取轮询器中所有注册进的serversocketchannel和socketchannel
Set<SelectionKey> set = selector.selectedKeys();
Iterator<SelectionKey> iterator = set.iterator();
while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
iterator.remove();
//如果选出来的channel有效
if (selectionKey.isValid()){
// ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel) selectionKey.channel();
//首先判断channel是不是可接收的,就是判断channel是不是serversocketchannel
if (selectionKey.isAcceptable()){
//未解决,放在上面就会报类型错误
ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel) selectionKey.channel();
//如果是serversocketchannel就把对应接收的通信socket,即socketchannel接受并注册到selector中
SocketChannel socketChannel = serverSocketChannel1.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector,SelectionKey.OP_READ);
//链接成功后从服务端发送的数据
String msgsend = "message";
byte[] bytes = msgsend.getBytes();
ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
byteBuffer.put(bytes);
byteBuffer.flip();
socketChannel.write(byteBuffer);
if (! byteBuffer.hasRemaining()){
System.out.println("message from server is send");
}
}
//如果channel可读,即是socketchannel
if (selectionKey.isReadable()){
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
//创建bytebuffer用来存放数据
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int readlen = socketChannel.read(byteBuffer);
if (readlen > 0){
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
String message = new String(bytes,0,readlen);
System.out.println("message is get + " + message);
}else if (readlen < 0){
selectionKey.cancel();
socketChannel.close();
}
}
}
}
}
}
if (selector != null){
selector.close();
}
}catch (IOException e) {
e.printStackTrace();
}
客户端建立
//创建客户端socket
Socket socket = new Socket();
//客户端连接至服务端
socket.connect(new InetSocketAddress("127.0.0.1",8099));
//以输出字节流的方式将本地数据输出至socket中
OutputStream outputStream = socket.getOutputStream();
// System.out.println(outputStream.getClass().getName());
//要发送的字符串信息
String str = "hello world";
//将字符串转化成字节流用outputstream进行输出
outputStream.write(str.getBytes());
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int readlen = inputStream.read(bytes);
System.out.println(new String(bytes,0,readlen));
if (outputStream != null){
outputStream.close();
}
if (inputStream != null){
inputStream.close();
}
socket.close();
}