(2)解决方案二(缓存Socket,轮询数据是否准备好)
- public class Server {
- public static void main(String[] args) throws InterruptedException {
- ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
-
- List<SocketChannel> socketList = new ArrayList<SocketChannel>();
- try {
- //Java为非阻塞设置的类
- ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
- serverSocketChannel.bind(new InetSocketAddress(8080));
- //设置为非阻塞
- serverSocketChannel.configureBlocking(false);
- while(true) {
- SocketChannel socketChannel = serverSocketChannel.accept();
- if(socketChannel==null) {
- //表示没人连接
- System.out.println("正在等待客户端请求连接...");
- Thread.sleep(5000);
- }else {
- System.out.println("当前接收到客户端请求连接...");
- socketList.add(socketChannel);
- }
- for(SocketChannel socket:socketList) {
- socket.configureBlocking(false);
- int effective = socket.read(byteBuffer);
- if(effective!=0) {
- byteBuffer.flip();//切换模式 写-->读
- String content = Charset.forName("UTF-8").decode(byteBuffer).toString();
- System.out.println("接收到消息:"+content);
- byteBuffer.clear();
- }else {
- System.out.println("当前未收到客户端消息");
- }
- }
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
(编辑:晋中站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|