服务端:

package com.yang.runnable;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator; public class GroupChat {
private Selector selector;
private ServerSocketChannel serverSocketChannel;
private static final int port=8801; public GroupChat() {
try {
selector=Selector.open();
serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
} public void listen() throws IOException { while (true){
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
if(key.isAcceptable()){
ServerSocketChannel serverSocketChannel = (ServerSocketChannel)key.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector,SelectionKey.OP_READ);
String userName = socketChannel.getRemoteAddress().toString();
System.out.println(userName+": 上线了。。。。。");
}
if(key.isReadable()){
SocketChannel sc = (SocketChannel)key.channel();
boolean flgRead = read(sc);
if(!flgRead){
System.out.println(sc.getRemoteAddress().toString()+"下线了。。。");
key.cancel();
}
}
iterator.remove();
}
}
} public boolean read(SocketChannel socketChannel) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
int read = socketChannel.read(buffer);
if(read==-1){
return false;
}
String msg = new String(buffer.array());
String userName = socketChannel.getRemoteAddress().toString();
System.out.println("收到"+userName+"发来的消息:"+msg);
dispatchet(socketChannel,msg);
return true;
} public void dispatchet(SocketChannel socketChannel,String msg){
Iterator<SelectionKey> iterator = selector.keys().iterator();
while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
SelectableChannel channel = selectionKey.channel();
if(channel instanceof SocketChannel && channel!=socketChannel){
SocketChannel sc=(SocketChannel)channel;
try {
sc.write(ByteBuffer.wrap(msg.getBytes()));
} catch (IOException e) {
try {
System.out.println(sc.getRemoteAddress().toString()+"下线了。。。");
} catch (IOException ex) {
ex.printStackTrace();
}
selectionKey.cancel();
e.printStackTrace();
}
}
} } public static void main(String[] args) throws IOException {
GroupChat groupChat = new GroupChat();
groupChat.listen();
} }

客户端:

package com.yang.xiao.hui;

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.Scanner; public class SocketClient {
private Selector selector;
private SocketChannel socketChannel;
private static final int port=8801; public SocketClient() {
try {
selector = Selector.open();
socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1",port));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessage(String message){
ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
try {
System.out.println("向服务端发送。。。。"+message);
socketChannel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
} } private void listen(){
try {
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
if(key.isReadable()){
SocketChannel channel =(SocketChannel) key.channel();
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
channel.read(byteBuffer);
System.out.println("收到服务器返回的:"+new String(byteBuffer.array()));
}
}
} catch (IOException e) {
e.printStackTrace();
} } public static void main(String[] args) {
SocketClient socketClient = new SocketClient();
new Thread(()->{
while (true){
socketClient.listen();
} }).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String message = scanner.next();
socketClient.sendMessage(message);
} } }

NIO 实现简单群聊功能的更多相关文章

  1. Java网络编程Demo,使用TCP 实现简单群聊功能GroupchatSimple,多个客户端输入消息,显示在服务端的控制台

    效果: 服务端 客户端 实现代码: 服务端 import java.io.IOException; import java.net.ServerSocket; import java.net.Sock ...

  2. 使用socket.io开发简单群聊功能

    1.新建package.json文件: { "name": "socket-chat-example", "version": " ...

  3. Java网络编程Demo,使用TCP 实现简单群聊功能Groupchat,创建一个服务端,使多个客户端都能收到消息

    效果图: 开启服务端 客户端一 客户端二 客户端三 实现代码: 客户端类 import java.io.IOException; import java.net.ServerSocket; impor ...

  4. Java-->实现群聊功能(C/S模式--TCP协议)

    --> Java 对TCP协议的支持: --> java.net包中定义了两个类ServerSocket 和Socket ,分别用来实现双向连接的server 端和client 端. -- ...

  5. day04-1群聊功能

    多用户即时通讯系统04 4.编码实现03 4.5功能实现-群聊功能实现 4.5.1思路分析 群聊的实现思路和私聊的实现非常类似. 不同的是:私聊时,服务端接收到消息后,只需要找出接收方的socket并 ...

  6. Asp.net SignalR 应用并实现群聊功能 开源代码

    ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程.实时 Web 功能是指这样一种功能:当所连接的客户端变得可用时服务 ...

  7. ASP.NET SignalR 与LayIM配合,轻松实现网站客服聊天室(四) 添加表情、群聊功能

    休息了两天,还是决定把这个尾巴给收了.本篇是最后一篇,也算是草草收尾吧.今天要加上表情功能和群聊.基本上就差不多了,其他功能,读者可以自行扩展或者优化.至于我写的代码方面,自己也没去重构.好的,我们开 ...

  8. netty实现群聊功能

    [概述] 实现一个网络群聊工具.参与聊天的客户端消息是通过服务端进行广播的. 主要由两块组成:聊天服务器端(ChatServer)和聊天客户端(ChatClient). 聊天服务器(ChatServe ...

  9. java项目-----客户端与客户端通信--实现群聊功能的代码

    这是这个网络聊天室项目的原理图: 很简单,首先ABCD是4个客户端,当A发送信息给服务器,服务器实现以广播的形式把信息全发给每个人---群发群聊 客户端代码: package com.aa; impo ...

随机推荐

  1. springmvc以及springboot中的拦截器配置

    拦截器两种实现   如果不同的controller中都需要拦截器,不能使用相同的拦截器,因为拦截器不能跨controller,这个时候只能为不同的controller配置不同的拦截器,每一个拦截器只能 ...

  2. Qt 如何使窗体初始最大化

    Qt 如何使窗体初始最大化 使用以下函数即可解决: void QWidget::setWindowState ( Qt::WindowStateswindowState ) 这样的函数,通过它可以设置 ...

  3. Orleans 知多少 | Orleans 中文文档上线

    Orleans 简介 Orleans是一个跨平台框架,用于构建健壮,可扩展的分布式应用程序 Orleans建立在.NET开发人员生产力的基础上,并将其带入了分布式应用程序的世界,例如云服务. Orle ...

  4. win环境下安装配置openCV-4.3.0

    win环境下安装openCV-4.3.0 首先下载 推荐国内镜像 官网太太太慢了 附上 下载地址 下载之后打开exe解压到目录都是常规操作 环境变量的配置 依次打开到系统变量的path 新建一个路径为 ...

  5. 力扣Leetcode 45. 跳跃游戏 II - 贪心思想

    这题是 55.跳跃游戏的升级版 力扣Leetcode 55. 跳跃游戏 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个元素代表你在该位置可以跳跃的最大长度. 你的目标是使用最少的跳跃 ...

  6. 08.简单学习redis哨兵主备切换和选举算法

    一.选举的授权 每次一个哨兵要做主备切换,首先需要quorum数量的哨兵认为odown,然后选举出一个哨兵来做切换,这个哨兵还得得到majority哨兵的授权,才能正式执行切换 如果quorum &l ...

  7. Labview学习之路(十一)日常编程技巧

    此文章用于记录自己在学习Labview过程中所用到的编程技巧,会一直更新下去. (一)移动控件 直接鼠标拖动. 按住shift键,鼠标移动,可以水平和竖直移动(取决于鼠标最开始的移动方向). 使用键盘 ...

  8. Spark RDD中Runtime流程解析

    一.Runtime架构图 (1)从Spark  Runtime的角度讲,包括五大核心对象:Master.Worker.Executor.Driver.CoarseGrainedExecutorBack ...

  9. vmware-workstation迁移虚拟机 15pro到12版本

    最近将测试的几台虚拟机进行了迁移,有几个点要注意,分享一下 1.环境介绍: 源服务器-ip-172.16.96.x 目标服务器-ip-172.16.96.x VMware版本-VMwareworkst ...

  10. POJ - 3851-Wormholes(SPFA判负环)

    A friend of yours, an inventor, has built a spaceship recently and wants to explore space with it. D ...