服务端:

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. SLS案例中心

    今日PV nginx日志查看今日的PV和昨日的对比,先通过count函数计算总的pv,再用compare函数得出今日的pv和昨日的同比. 通过单值图进行展示,显示值为20.381Mil,对比值为-2% ...

  2. 学习seo技术要不断地扩大思维和思路

    http://www.wocaoseo.com/thread-148-1-1.html        目前学习seo技术的人员是越来越多了,通过查看seo这个词的指数,就能发现一些状况,从最初的每天3 ...

  3. WebApis中DOM执行机制的认识

    1.1. 节点操作 1.1.1 删除节点 node.removeChild() 方法从 node节点中删除一个子节点,返回删除的节点. <button>删除</button> ...

  4. 华为手机logcat中不显示log.e以下级别日志的解决方法

    (1) 进入拨号界面输入:*#*#2846579#*#* (2) 进入“后台设置” ——>“LOG设置” (3) 点击选择“AP日志” (4) 部分手机可能需要重启.

  5. [BUUOJ记录] [GXYCTF2019]Ping Ping Ping

    主要考察RCE的防护绕过,感觉考的还是比较全的 先构造Payload: ?ip=127.0.0.1;ls 看到目录下有两个文件,fuzz一下发现过滤了 空格 / + * ? { } ( ) [ ]等符 ...

  6. Azure Blob (三)参数设置说明

    一,引言 上一篇将 Azure Blob 存储的时候,有使用到一个 .NET  Core Web 项目,通过代码的方式进行操作 Azure Blob 的数据,接着上一篇的内容,今天继续看一下代码,具体 ...

  7. 《Offer一箩筐》求职之前你必须知道的 4 件事!!

    「MoreThanJava」 宣扬的是 「学习,不止 CODE」. 如果觉得 「不错」 的朋友,欢迎 「关注 + 留言 + 分享」,文末有完整的获取链接,您的支持是我前进的最大的动力! Hi~ 这里是 ...

  8. mysql InnoDB引擎是否支持hash索引

    看一下mysql官方文档:https://dev.mysql.com/doc/refman/5.7/en/create-index.html , 从上面的图中可以得知,mysql 是支持hash索引的 ...

  9. docker打包项目

    nginx镜像制作实战 docker容器的主业 docker理念里,容器启动时,应当为它指定主业是什么,如nginx容器主业就是nginx代理服务,tomcat容器就是web服务等等 1.容器创建时, ...

  10. python 模块安装导入

    一.定义 python模块就是一个.py文件,一个模块中可以有多个函数,在使用模块时,只需要import下,就可以使用模块中的函数功能.import模块的过程相当于把这个py文件中的所有内容都执行一遍 ...