欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java?NIO實(shí)現(xiàn)聊天功能

 更新時間:2021年11月24日 12:13:09   作者:TCH987551623  
這篇文章主要為大家詳細(xì)介紹了Java?NIO實(shí)現(xiàn)聊天功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了Java NIO實(shí)現(xiàn)聊天功能的具體代碼,供大家參考,具體內(nèi)容如下

server code :?

package com.tch.test.nio;
 
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
 
public class NioServer {
 
 private SocketChannel socketChannel = null;
 private Set<SelectionKey> selectionKeys = null;
 private Iterator<SelectionKey> iterator = null;
 private Iterator<SocketChannel> iterator2 = null;
 private SelectionKey selectionKey = null;
 
 public static void main(String[] args) {
  new NioServer().start();
 }
 
 private void start(){
  try {
   //create serverSocketChannel
   ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
   //bind the serverSocketChannel to a port
   serverSocketChannel.bind(new InetSocketAddress(7878));
   //when using selector ,should config the blocking mode of serverSocketChannel to non-blocking
   serverSocketChannel.configureBlocking(false);
   //create a selector to manage all the channels
   Selector selector = Selector.open();
   //reigst the serverSocketChannel to the selector(interest in accept event)
   serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
   //create a list to store all the SocketChannels
   List<SocketChannel> clients = new ArrayList<SocketChannel>();
   //create a ByteBuffer to store data
   ByteBuffer buffer = ByteBuffer.allocate(1024);
   while(true){
    //this method will block until at least one of the interested events is ready 
    int ready = selector.select();
    if(ready > 0){//means at least one of the interested events is ready 
     selectionKeys = selector.selectedKeys();
     iterator = selectionKeys.iterator();
     while(iterator.hasNext()){
                        //the selectionKey contains the channel and the event which the channel is interested in 
                        selectionKey = iterator.next();
                        //accept event , means new client reaches
                        if(selectionKey.isAcceptable()){
                            //handle new client
                            ServerSocketChannel serverSocketChannel2 = (ServerSocketChannel)selectionKey.channel();
                            socketChannel = serverSocketChannel2.accept();
                            //when using selector , should config the blocking mode of socketChannel to non-blocking
                            socketChannel.configureBlocking(false);
                            //regist the socketChannel to the selector
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            //add to client list
                            clients.add(socketChannel);
                        }else if(selectionKey.isReadable()){
                            //read message from client
                            socketChannel = (SocketChannel)selectionKey.channel();
                            buffer.clear();
                            try {
                                socketChannel.read(buffer);
                                buffer.flip();
                                //send message to every client
                                iterator2 = clients.iterator();
                                SocketChannel socketChannel2 = null;
                                while(iterator2.hasNext()){
                                    socketChannel2 = iterator2.next();
                                    while(buffer.hasRemaining()){
                                        socketChannel2.write(buffer);
                                    }
                                    //rewind method makes the buffer ready to the next read operation
                                    buffer.rewind();
                                }
                            } catch (IOException e) {
                                // IOException occured on the channel, remove from channel list
                                e.printStackTrace();
                                // Note: close the channel
                                socketChannel.close();
                                iterator2 = clients.iterator();
                                while(iterator2.hasNext()){
                                    if(socketChannel == iterator2.next()){
                                        // remove the channel
                                        iterator2.remove();
                                        System.out.println("remove the closed channel from client list ...");
                                        break;
                                    }
                                }
                            }
                        }
                        //important , remember to remove the channel after all the operations. so that the next selector.select() will 
                        //return this channel again .
      iterator.remove();
     }
    }
   }
  } catch (ClosedChannelException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
}

client code :?

package com.tch.nio.test;
 
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
public class NioClient extends JFrame{
 
 private static final long serialVersionUID = 1L;
 private JTextArea area = new JTextArea("content :");
 private JTextField textField = new JTextField("textfield:");
 private JButton button = new JButton("send");
 private SocketChannel socketChannel = null;
 private ByteBuffer buffer = ByteBuffer.allocate(1024);
 private ByteBuffer buffer2 = ByteBuffer.allocate(1024);
 private String message = null;
 
 public static void main(String[] args) throws Exception {
  NioClient client = new NioClient();
  client.start();
 }
 
 private void start() throws IOException{
  setBounds(200, 200, 300, 400);
  setLayout(new GridLayout(3, 1));
  add(area);
  add(textField);
  //create a socketChannel and connect to the specified address
  socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 7878));
  //when using selector , should config the blocking mode of socketChannel to non-blocking
  socketChannel.configureBlocking(false);
  button.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent event) {
    try {
     message = textField.getText();
     textField.setText("");
     //send message to server
     buffer.put(message.getBytes("utf-8"));
     buffer.flip();
     while(buffer.hasRemaining()){
      socketChannel.write(buffer);
     }
     buffer.clear();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
  add(button);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  setVisible(true);
  Set<SelectionKey> selectionKeys = null;
  Iterator<SelectionKey> iterator = null;
  SelectionKey selectionKey = null;
  Selector selector = Selector.open();
  //reigst the socketChannel to the selector(interest in read event)
  socketChannel.register(selector, SelectionKey.OP_READ);
  while(true){
   //this method will block until at least one of the interested events is ready 
   int ready = selector.select();
   if(ready > 0){//means at least one of the interested events is ready 
    selectionKeys = selector.selectedKeys();
    iterator = selectionKeys.iterator();
    while(iterator.hasNext()){
     selectionKey = iterator.next();
     //read message from server ,then append the message to textarea
     if(selectionKey.isReadable()){
      socketChannel.read(buffer2);
      buffer2.flip();
      area.setText(area.getText().trim()+"\n"+new String(buffer2.array(),0,buffer2.limit(),"utf-8"));
      buffer2.clear();
     }
     //important , remember to remove the channel after all the operations. so that the next selector.select() will 
     //return this channel again .
     iterator.remove();
    }
   }
  }
 }
 
}

run server first , then is client , type message and send , ok

使用Mina實(shí)現(xiàn)聊天:

server:

package com.tch.test.jms.origin.server;
 
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class MyServer {
 
 private static final Logger LOGGER = LoggerFactory.getLogger(MyServer.class);
 private List<IoSession> clientSessionList = new ArrayList<IoSession>();
 
 public static void main(String[] args) {
     
  IoAcceptor acceptor = new NioSocketAcceptor();
 
  acceptor.getFilterChain().addLast("logger", new LoggingFilter());
  acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
 
  acceptor.setHandler(new MyServer().new MyServerIoHandler());
  
  try {
   acceptor.bind(new InetSocketAddress(10000));
  } catch (IOException ex) {
   LOGGER.error(ex.getMessage(), ex);
  }
 }
 
 class MyServerIoHandler extends IoHandlerAdapter{
        
        @Override
        public void sessionCreated(IoSession session) throws Exception {
            LOGGER.info("sessionCreated");
        }
        
        @Override
        public void sessionOpened(IoSession session) throws Exception {
            LOGGER.info("sessionOpened");
            if(! clientSessionList.contains(session)){
                clientSessionList.add(session);
            }
        }
 
        @Override
        public void sessionClosed(IoSession session) throws Exception {
            LOGGER.info("sessionClosed");
            clientSessionList.remove(session);
        }
 
        @Override
        public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
            LOGGER.info("sessionIdle");
        }
 
        @Override
        public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
            LOGGER.error(cause.getMessage(), cause);
            session.close(true);
            clientSessionList.remove(session);
        }
 
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            LOGGER.info("messageReceived:" + message);
            for(IoSession clientSession : clientSessionList){
                clientSession.write(message);
            }
        }
 
        @Override
        public void messageSent(IoSession session, Object message) throws Exception {
            LOGGER.info("messageSent:" + message);
        }
    }
}

client :

package com.tch.test.jms.origin.client;
 
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class NioClient extends JFrame{
    private static final Logger LOGGER = LoggerFactory.getLogger(NioClient.class);
 private static final long serialVersionUID = 1L;
 private JTextArea area = new JTextArea("content :");
 private JTextField textField = new JTextField("textfield:");
 private JButton button = new JButton("send");
 private String message = null;
 private MyClientIoHandler handler;
 private IoSession session;
 
 public static void main(String[] args) throws Exception {
  NioClient client = new NioClient();
  client.start();
 }
 
 private void start() throws IOException{
  setBounds(200, 200, 300, 400);
  setLayout(new GridLayout(3, 1));
  add(area);
  add(textField);
  
  IoConnector connector = new NioSocketConnector();
        connector.setConnectTimeoutMillis(10 * 1000);
        
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
        
        handler = new MyClientIoHandler(this);
        connector.setHandler(handler);
  
  button.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent event) {
       sendMessage();
   }
  });
  add(button);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  setVisible(true);
  
  IoSession session = null;
        try {
            ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 10000));
            future.awaitUninterruptibly();
            session = future.getSession();
        } catch (RuntimeIoException e) {
            LOGGER.error(e.getMessage(), e);
        }
        session.getCloseFuture().awaitUninterruptibly();
        connector.dispose();
 }
 
 private void sendMessage() {
        try {
            message = textField.getText();
            textField.setText("");
            if(session == null || ! session.isConnected()){
                throw new RuntimeException("session is null");
            }
            session.write(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 class MyClientIoHandler extends IoHandlerAdapter{
     private NioClient client;
        public MyClientIoHandler(NioClient client){
            this.client = client;
        }
        @Override
        public void sessionCreated(IoSession session) throws Exception {
            LOGGER.info("sessionCreated");
        }
 
        @Override
        public void sessionOpened(IoSession session) throws Exception {
            LOGGER.info("sessionOpened");
            client.session = session;
        }
 
        @Override
        public void sessionClosed(IoSession session) throws Exception {
            LOGGER.info("sessionClosed");
        }
 
        @Override
        public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
            LOGGER.info("sessionIdle");
        }
 
        @Override
        public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
            LOGGER.error(cause.getMessage(), cause);
            session.close(true);
        }
 
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            LOGGER.info("messageReceived: " + message);
            if (message.toString().equalsIgnoreCase("Bye")) {
                session.close(true);
            }
            area.setText(area.getText().trim()+"\n"+message);
        }
 
        @Override
        public void messageSent(IoSession session, Object message) throws Exception {
            LOGGER.info("messageSent: " + message);
        }
    }
 
}

OK.

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java精品項目瑞吉外賣之后端登錄功能篇

    Java精品項目瑞吉外賣之后端登錄功能篇

    這篇文章主要為大家詳細(xì)介紹了java精品項目-瑞吉外賣訂餐系統(tǒng),此項目過大,分為多章獨(dú)立講解,本篇內(nèi)容為后端登錄功能的實(shí)現(xiàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • springboot處理異常的5種方式

    springboot處理異常的5種方式

    本文主要介紹了springboot處理異常的5種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • Java 自定義Spring框架以及Spring框架的基本使用

    Java 自定義Spring框架以及Spring框架的基本使用

    Spring框架是由于軟件開發(fā)的復(fù)雜性而創(chuàng)建的。Spring使用的是基本的JavaBean來完成以前只可能由EJB完成的事情。然而,Spring的用途不僅僅限于服務(wù)器端的開發(fā)
    2021-10-10
  • Spring-AOP @AspectJ切點(diǎn)函數(shù)之@annotation()用法

    Spring-AOP @AspectJ切點(diǎn)函數(shù)之@annotation()用法

    這篇文章主要介紹了Spring-AOP @AspectJ切點(diǎn)函數(shù)之@annotation()用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • SpringBoot根據(jù)目錄結(jié)構(gòu)自動生成路由前綴的實(shí)現(xiàn)代碼

    SpringBoot根據(jù)目錄結(jié)構(gòu)自動生成路由前綴的實(shí)現(xiàn)代碼

    本文介紹如何根據(jù)目錄結(jié)構(gòu)給RequestMapping添加路由前綴,具體實(shí)現(xiàn)方法,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2021-08-08
  • 詳解Java多線程處理List數(shù)據(jù)

    詳解Java多線程處理List數(shù)據(jù)

    這篇文章主要介紹了Java多線程處理List數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • Java 集合中關(guān)于Iterator和ListIterator的用法說明

    Java 集合中關(guān)于Iterator和ListIterator的用法說明

    這篇文章主要介紹了Java 集合中關(guān)于Iterator和ListIterator的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • 精通Java List 按字段提取對象

    精通Java List 按字段提取對象

    這篇文章主要介紹了精通Java List 按字段提取對象的相關(guān)資料,需要的朋友可以參考下
    2023-11-11
  • Jmeter自定義函數(shù)base64加密實(shí)現(xiàn)過程解析

    Jmeter自定義函數(shù)base64加密實(shí)現(xiàn)過程解析

    這篇文章主要介紹了Jmeter自定義函數(shù)base64加密實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • Java常用正則表達(dá)式驗(yàn)證類完整實(shí)例【郵箱、URL、IP、電話、身份證等】

    Java常用正則表達(dá)式驗(yàn)證類完整實(shí)例【郵箱、URL、IP、電話、身份證等】

    這篇文章主要介紹了Java常用正則表達(dá)式驗(yàn)證類,結(jié)合完整實(shí)例形式分析了Java針對郵箱、網(wǎng)址URL、IP地址、電話、身份證等正則驗(yàn)證相關(guān)操作技巧,需要的朋友可以參考下
    2018-12-12

最新評論