广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java NIO实现聊天功能
  • 659
分享到

Java NIO实现聊天功能

2024-04-02 19:04:59 659人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

本文实例为大家分享了Java NIO实现聊天功能的具体代码,供大家参考,具体内容如下 server code :  package com.tch.test.nio; imp

本文实例为大家分享了Java NIO实现聊天功能的具体代码,供大家参考,具体内容如下

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实现聊天:

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.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: Java NIO实现聊天功能

本文链接: https://www.lsjlt.com/news/158180.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Java NIO实现聊天功能
    本文实例为大家分享了Java NIO实现聊天功能的具体代码,供大家参考,具体内容如下 server code :  package com.tch.test.nio; imp...
    99+
    2022-11-12
  • Java NIO实现聊天室功能
    本文实例为大家分享了Java NIO实现聊天室功能的具体代码,供大家参考,具体内容如下 代码里面已经包含了必要的注释,这里不详述了。实现了基本的聊天室功能。 常量类: publi...
    99+
    2022-11-12
  • Java基于NIO实现聊天室功能
    本文实例为大家分享了Java基于NIO实现聊天室功能的具体代码,供大家参考,具体内容如下 Sever端 package com.qst.one; import java.io....
    99+
    2022-11-12
  • Java NIO怎么实现聊天室功能
    这篇文章主要介绍了Java NIO怎么实现聊天室功能,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。具体内容如下代码里面已经包含了必要的注释,这里不详述了。实现了基本...
    99+
    2023-06-21
  • Java基于NIO怎么实现聊天室功能
    Java基于NIO怎么实现聊天室功能,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。Sever端package com.qst.one;import java...
    99+
    2023-06-21
  • Java NIO实现聊天系统
    使用Java的NIO写的一个小的聊天系统,供大家参考,具体内容如下 一、服务端 public class GroupChatServer { // 定义相关的属性 ...
    99+
    2022-11-12
  • Java怎么实现NIO聊天室
    这篇文章给大家分享的是有关Java怎么实现NIO聊天室的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。功能介绍功能:群聊+私发+上线提醒+下线提醒+查询在线用户文件Utils需要用maven导入下面两个包 ...
    99+
    2023-06-15
  • Java NIO实现多人聊天室
    本文实例为大家分享了Java NIO实现多人聊天室的具体代码,供大家参考,具体内容如下 1. 服务器端代码 ChatServer类: package nio.test.serve...
    99+
    2022-11-12
  • Java基于NIO实现群聊功能
    本文实例为大家分享了Java基于NIO实现群聊功能的具体代码,供大家参考,具体内容如下 一、群聊服务器 package com.dashu.netty.group_chat; ...
    99+
    2022-11-12
  • java NIO实现简单聊天程序
    本文实例为大家分享了java NIO实现简单聊天程序的具体代码,供大家参考,具体内容如下 服务端 功能: 1、接受客户端连接 2、发送消息 3、读取客户端消息 Server.jav...
    99+
    2022-11-12
  • java实现简易聊天功能
    本文实例为大家分享了java实现简易聊天功能的具体代码,供大家参考,具体内容如下 应用客户端和服务端通过控制台的输入输出实现简易聊天功能 思路: 1.创建服务端类ChatServer...
    99+
    2022-11-13
  • Java实现在线聊天功能
    本文实例为大家分享了Java实现在线聊天功能的具体代码,供大家参考,具体内容如下 效果 关键代码 创建Client.java import java.io.IOException;...
    99+
    2022-11-13
  • Java Socket实现聊天室功能
    本文实例为大家分享了Java Socket实现聊天室的具体代码,供大家参考,具体内容如下 1 创建登录判断类UserLogin import java.util.HashSet; i...
    99+
    2022-11-13
  • java怎么实现聊天功能
    要实现聊天功能,可以使用Java中的Socket编程和多线程技术。首先,需要创建一个服务器端和多个客户端。服务器端负责接收和转发客户端之间的消息,而客户端则负责发送和接收消息。服务器端的代码示例:```javaimport java.i...
    99+
    2023-08-11
    java
  • Java聊天室之实现聊天室服务端功能
    目录一、题目描述二、解题思路三、代码详解多学一个知识点一、题目描述 题目实现:实现聊天室服务器端功能。运行程序,服务端等待客户端连接,并显示客户端的连接信息。 二、解题思路 创建一个...
    99+
    2022-11-13
    Java实现聊天室 Java 聊天室 Java 服务端
  • Java聊天室之实现聊天室客户端功能
    目录一、题目描述二、解题思路三、代码详解一、题目描述 题目实现:实现聊天室客户端。运行程序,用户登录服务器后,可以从用户列表中选择单个用户进行聊天,也可以选择多个用户进行聊天。 二、...
    99+
    2022-11-13
    Java实现聊天室 Java 聊天室 Java 客户端
  • Java NIO怎么实现聊天室程序
    本文小编为大家详细介绍“Java NIO怎么实现聊天室程序”,内容详细,步骤清晰,细节处理妥当,希望这篇“Java NIO怎么实现聊天室程序”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。服务端:package&n...
    99+
    2023-06-17
  • java实现多客户聊天功能
    java 实现多客户端聊天(TCP),供大家参考,具体内容如下 1. 编程思想: 1)、要想实现多客户端聊天,首先需要有多个客户端,而这些客户端需要随时发送消息和接受消息,所以收发消...
    99+
    2022-11-12
  • Java实现NIO聊天室的示例代码(群聊+私聊)
    目录功能介绍文件UtilsFinalValueMessageNioServerNioClient功能介绍 功能:群聊+私发+上线提醒+下线提醒+查询在线用户 文件 U...
    99+
    2022-11-12
  • Java实现局域网聊天室功能(私聊、群聊)
    本文实例为大家分享了Java实现局域网聊天室功能的具体代码,供大家参考,具体内容如下 Server 服务端 import java.io.IOException; import ja...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作