NIO 实现简单群聊功能
服务端:
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 实现简单群聊功能的更多相关文章
- Java网络编程Demo,使用TCP 实现简单群聊功能GroupchatSimple,多个客户端输入消息,显示在服务端的控制台
效果: 服务端 客户端 实现代码: 服务端 import java.io.IOException; import java.net.ServerSocket; import java.net.Sock ...
- 使用socket.io开发简单群聊功能
1.新建package.json文件: { "name": "socket-chat-example", "version": " ...
- Java网络编程Demo,使用TCP 实现简单群聊功能Groupchat,创建一个服务端,使多个客户端都能收到消息
效果图: 开启服务端 客户端一 客户端二 客户端三 实现代码: 客户端类 import java.io.IOException; import java.net.ServerSocket; impor ...
- Java-->实现群聊功能(C/S模式--TCP协议)
--> Java 对TCP协议的支持: --> java.net包中定义了两个类ServerSocket 和Socket ,分别用来实现双向连接的server 端和client 端. -- ...
- day04-1群聊功能
多用户即时通讯系统04 4.编码实现03 4.5功能实现-群聊功能实现 4.5.1思路分析 群聊的实现思路和私聊的实现非常类似. 不同的是:私聊时,服务端接收到消息后,只需要找出接收方的socket并 ...
- Asp.net SignalR 应用并实现群聊功能 开源代码
ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程.实时 Web 功能是指这样一种功能:当所连接的客户端变得可用时服务 ...
- ASP.NET SignalR 与LayIM配合,轻松实现网站客服聊天室(四) 添加表情、群聊功能
休息了两天,还是决定把这个尾巴给收了.本篇是最后一篇,也算是草草收尾吧.今天要加上表情功能和群聊.基本上就差不多了,其他功能,读者可以自行扩展或者优化.至于我写的代码方面,自己也没去重构.好的,我们开 ...
- netty实现群聊功能
[概述] 实现一个网络群聊工具.参与聊天的客户端消息是通过服务端进行广播的. 主要由两块组成:聊天服务器端(ChatServer)和聊天客户端(ChatClient). 聊天服务器(ChatServe ...
- java项目-----客户端与客户端通信--实现群聊功能的代码
这是这个网络聊天室项目的原理图: 很简单,首先ABCD是4个客户端,当A发送信息给服务器,服务器实现以广播的形式把信息全发给每个人---群发群聊 客户端代码: package com.aa; impo ...
随机推荐
- Java小菜求职记-以前在Dubbo踩的坑,这次全被问到了,这下舒服了
前传 小林求职记(五)上来就一连串的分布式缓存提问,我有点上头.... 终于,在小林的努力下,获得了王哥公司那边的offer,但是因为薪水没有谈妥,小林又重新进入了求职的旅途,在经历了多次求职过程之后 ...
- Linux环境下MySQL 5.6安装与配置----亲测有效----纯离线安装
一.安装MySQL 1.下载安装包 mysql-5.6.40-linux-glibc2.12-x86_64.tar.gz 下载地址: https://dev.mysql.com/get/Downloa ...
- ssm框架之springMVC拦截器
1拦截器概述 1.1什么是拦截器? springMVC中的拦截器(Interceptor)类似于servlet中的过滤器(Filter),它主要用于拦截用户请求并作相应的处理.例如通过拦截器可以进行权 ...
- 项目介入EF Core
目前.Net主流的ORM有SqlSugar.Entity Framework.Dapper,其它的我就不列举了.其实和Java那边ibatis相比,他们都比较轻量.之前用ibatis开发,真的很麻烦, ...
- React-Native知识点相关
React-Native相关 一,为什么要使用React-native? Hybrird的首屏时间太慢,白屏太久,影响用户体验: 原生native开发成本较高: 这里补充一点Webview的性能优化: ...
- 攻防世界——web新手练习区解题记录<1>(1-4题)
web新手练习区一至四题 第一题view_source: 题目说右键不管用了,我们先获取在线场景来看一看,我们看到这样一个网页,并且右键确实点了没什么反应,而用到右键一般就是查看网页源码 用快捷键(F ...
- Cocos Creator 性能优化:DrawCall
前言 在游戏开发中,DrawCall 作为一个非常重要的性能指标,直接影响游戏的整体性能表现. 无论是 Cocos Creator.Unity.Unreal 还是其他游戏引擎,只要说到游戏性能优化,D ...
- hyperledger fabric 智能合约开发
开发步奏: 1.创建教育联盟 2.区块链服务平台自动生成通道id 3.区块链网络服务人员通过命令行在区块链网络中创建对应通道 4.创建相关教育组织 5.邀请相关组织加入联盟 6.区块链网络管理人员通过 ...
- touchstart 事件与 click 事件的冲突
const clickEvent = (function() { if ('ontouchstart' in document.documentElement === true) retu ...
- kickstart半自动安装centos系统与pxe自动安装centos系统
一.kickstart半自动安装centos系统 关闭防火墙,关闭selinux,使用system-config-kickstart生成kickstart配置文件,启动xmanger-Passive ...