服务端:

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. 【Spring】使用@Profile注解实现开发、测试和生产环境的配置和切换,看完这篇我彻底会了!!

    写在前面 在实际的企业开发环境中,往往都会将环境分为:开发环境.测试环境和生产环境,而每个环境基本上都是互相隔离的,也就是说,开发环境.测试环境和生产环境是互不相通的.在以前的开发过程中,如果开发人员 ...

  2. [C#.NET 拾遗补漏]08:强大的LINQ

    大家好,这是 [C#.NET 拾遗补漏] 系列的第 08 篇文章,今天讲 C# 强大的 LINQ 查询.LINQ 是我最喜欢的 C# 语言特性之一. LINQ 是 Language INtegrate ...

  3. LinuxIP配置方法

    一.双网卡双IP. eth0为电信,eth1为联通. # cd /etc/sysconfig/network-scripts/ # vi ifcfg-eth0 DEVICE=eth0 HWADDR=0 ...

  4. 如何自制WC3地形纹理贴图

    http://world-editor-tutorials.thehelper.net/tilesets.php https://wenku.baidu.com/view/e761c953cc1755 ...

  5. opencv-python函数

    opencv-python读取.展示和存储图像 1.imshow函数 imshow函数作用是在窗口中显示图像,窗口自动适合于图像大小,我们也可以通过imutils模块调整显示图像的窗口的大小.函数官方 ...

  6. 20190925-02配置redis服务在后台启动 000 023

    多端口要加 -p 可以进入指定端口

  7. Eclipse插件打开编辑器

    今天终于可以闲一天,想来想去就乱写点东西吧,说不定对有些新人有点帮助呢-_- 用Eclipse API的方式来打开编辑器,可能对任何一个插件开发者都不是很陌生的操作了.但是,还是建议你忍着看一下,全当 ...

  8. leetcode刷题-46全排列

    题目 给定一个 没有重复 数字的序列,返回其所有可能的全排列. 思路 回溯算法 不断取出字符,对剩余字符进行选择 实现 class Solution: def permute(self, nums: ...

  9. UBer面向领域的微服务体系架构实践

    介绍 最近,人们对面向服务的系统架构和微服务系统架构的缺点进行了大量的讨论.尽管仅仅在几年前,由于微服务体系架构提供了许多好处,如独立部署的灵活性.明确的所有权.提高系统稳定性以及更好地分离关注点等, ...

  10. Java类加载机制()

    Java类加载机制(转载) 概述 在开始正文之前,我们先看两张图 .Java平台的理解?Java最显著的特性?Java是解释执行? 先看一下java程序的执行流程图 再看一下jvm的大致物理结构图 本 ...