服务端:

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. 《Head First 设计模式》:外观模式

    正文 一.定义 外观模式提供了一个统一的接口,用来访问子系统中的一群接口.外观定义了一个高层接口,让子系统更容易使用. 要点: 外观模式将一个或数个类的复杂的一切都隐藏在背后,只显露出一个干净美好的外 ...

  2. java23种设计模式—— 二、单例模式

    源码在我的github和gitee中获取 介绍 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一.这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式. ...

  3. Cassandra社区是怎么测试4.0的

    点击查看活动录像,获取更多技术细节. Cassandra社区是怎么测试4.0的 Cassandra 4.0的目标就是成为史上最稳定的版本.为了达到这个目的,我们需要用很多方法和工具进行测试.我今天主要 ...

  4. 水滴app

    在选择了软件工程专业之后,指导教师也让我们参加到了学长学姐的作业之中来,使用学长学姐们的软件并写出自己的使用评价以及自己的一些小评价. 这体验的是第三十二组学长们的软件,他们的队名是自然选择,他们做的 ...

  5. Qt 关于图片打开,另存为,保存到指定位置操作

    Qt 关于图片打开,另存为,保存到指定位置操作(转载) 在头文件mainwindow.h中先声明以下类: 1 #include <QImage> 2 #include <QPixma ...

  6. 单元测试利器Mockito框架

    什么是Mock Mock 的中文译为仿制的,模拟的,虚假的.对于测试框架来说,即构造出一个模拟/虚假的对象,使我们的测试能顺利进行下去. Mock 测试就是在测试过程中,对于某些 不容易构造(如 Ht ...

  7. WPF实现的加载动画

    2020-09-03 09:43:30 xaml代码 <Grid x:Name="LayoutRoot" Background="Transparent" ...

  8. Codeforces1393 题解(A-D)

    AC代码 A. Rainbow Dash, Fluttershy and Chess Coloring 可以推导出\(f_1 = 1, f_2 = 2, ..., f_n = f_{n - 2} + ...

  9. Codeforces 1337C Linova and Kingdom

    题意 给你一颗有根树,你要选择\(k\)个点,最大化\(\sum_{i \in S} val_i\),其中\(S\)是被选点的集合,\(val_i\)等于节点\(i\)到根的路径上未被选择点的个数. ...

  10. 04async await

    async async 函数返回值是一个promise对象,promise对象的状态由async函数的返回值决定   //函数的三种定义 async function hello() { return ...