1、创建maven项目,在pom.xml中引入netty的jar包

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cppdy</groupId>
<artifactId>NettyDemo</artifactId>
<version>0.0.1-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.32.Final</version>
</dependency>
</dependencies> </project>

2、创建server处理程序类

package com.cppdy.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; public class ChatServerHandler extends SimpleChannelInboundHandler<String>{ @Override
protected void channelRead0(ChannelHandlerContext arg0, String msg) throws Exception { System.out.println(msg);
} }

3、创建server初始化类

package com.cppdy.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; public class ChatServerInit extends ChannelInitializer<SocketChannel>{ @Override
protected void initChannel(SocketChannel sc) throws Exception { ChannelPipeline pipeline = sc.pipeline();
pipeline.addLast("decoder",new StringDecoder());
pipeline.addLast("encoder",new StringEncoder());
pipeline.addLast("handler",new ChatServerHandler());
} }

4、创建server启动类

package com.cppdy.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel; public class ChatServer { public static void main(String[] args) {
NioEventLoopGroup boss = new NioEventLoopGroup();
NioEventLoopGroup worker = new NioEventLoopGroup(); try {
ServerBootstrap b = new ServerBootstrap();
b.group(boss, worker).channel(NioServerSocketChannel.class).childHandler(new ChatServerInit())
.option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); System.out.println("服务端启动啦……"); ChannelFuture sync = b.bind(8080).sync();
sync.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}

5、创建client处理程序类

package com.cppdy.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; public class ChatClientHandler extends SimpleChannelInboundHandler<String> { @Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println(msg);
} }

6、创建client初始化类

package com.cppdy.client;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; public class ChatClientInit extends ChannelInitializer<SocketChannel> { @Override
protected void initChannel(SocketChannel sc) throws Exception { ChannelPipeline pipeline = sc.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new ChatClientHandler()); } }

7、创建client启动类

package com.cppdy.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress; import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel; public class ChatClient { public static void main(String[] args) {
NioEventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class)
.handler(new ChatClientInit());
Channel channel = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080)).sync().channel();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
channel.writeAndFlush(bufferedReader.readLine() + "\r\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
}

8、先启动ChatServer类,再启动ChatClient类,就可以模拟发送消息功能。

Netty简单聊天室的更多相关文章

  1. 基于Server-Sent Event的简单聊天室 Web 2.0时代,即时通信已经成为必不可少的网站功能,那实现Web即时通信的机制有哪些呢?在这门项目课中我们将一一介绍。最后我们将会实现一个基于Server-Sent Event和Flask简单的在线聊天室。

    基于Server-Sent Event的简单聊天室 Web 2.0时代,即时通信已经成为必不可少的网站功能,那实现Web即时通信的机制有哪些呢?在这门项目课中我们将一一介绍.最后我们将会实现一个基于S ...

  2. Python Socket 简单聊天室2

    上篇文章写了一个简单的单线程的一问一答的简单聊天室.这次我们使用SocketServer模块搭建一个多线程异步的聊天室. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...

  3. Asp.Net SignalR - 简单聊天室实现

    简单聊天室 使用持久链接类我们就可以做一些即时通讯的应用了,我使用Group做了一个简单的聊天室,先上图技术细节下面再讲 可以加入聊天室.创建聊天室.发送消息,下面就说说我是如何通过Group做出来的 ...

  4. SpringBoot 搭建简单聊天室

    SpringBoot 搭建简单聊天室(queue 点对点) 1.引用 SpringBoot 搭建 WebSocket 链接 https://www.cnblogs.com/yi1036943655/p ...

  5. ASP.NET SingalR + MongoDB 实现简单聊天室(一):搭建基本框架

    ASP.NET SingalR不多介绍.让我介绍不如看官网,我这里就是直接上源代码,当然代码还是写的比较简单的,考虑的也少,希望各位技友多多提意见. 先简单介绍聊天室功能: 用户加入聊天室,自动给用户 ...

  6. 利用socket.io+nodejs打造简单聊天室

    代码地址如下:http://www.demodashi.com/demo/11579.html 界面展示: 首先展示demo的结果界面,只是简单消息的发送和接收,包括发送文字和发送图片. ws说明: ...

  7. C#实例之简单聊天室(状态管理)

    前言        状态管理是在同一页或不同页的多个请求发生时,维护状态和页信息的过程.因为Web应用程序的通信协议使用了无状态的HTTP协议,所以当客户端请求页面时,ASP.NET服务器端都会重新生 ...

  8. java web利用mvc结构实现简单聊天室功能

    简单聊天室采用各种内部对象不适用数据库实现. 一个聊天室要实现的基本功能是:         1.用户登录进入聊天室, 2.用户发言 3.用户可以看见别人发言 刚才算是简单的需求分析了,现在就应该是进 ...

  9. Netty 系列八(基于 WebSocket 的简单聊天室).

    一.前言 之前写过一篇 Spring 集成 WebSocket 协议的文章 —— Spring消息之WebSocket ,所以对于 WebSocket 协议的介绍就不多说了,可以参考这篇文章.这里只做 ...

随机推荐

  1. luogu P3175 [HAOI2015]按位或

    传送门 如果每个位置上的数字的意义是这个位置被加进集合的最早时间,那么我们要求的就是集合中最大数的期望,使用Min-Max容斥,\(E(max(S))=\sum_{T\subset S}(-1)^{| ...

  2. Linux/Windows双系统引导修复

    安装双系统建议先安装windows,然后在安装Linux,使用Linux(grub2)引导双系统 如果重新安装了windows,则无法引导进入linux,需要修复引导 在windows下安装easyB ...

  3. 第20月第4天 pycharm utf-8

    1.运行python %run a.py 运行 https://blog.csdn.net/little_bobo/article/details/78982412 2.UnicodeDecodeEr ...

  4. linux全部替换命令学习

    :%s/准备替换内容/新内容/g 可以使用 # 作为分隔符,此时中间出现的 / 不会作为分隔符 :%s#vivian/#sky/#g 替换 vivian/ 为 sky/ :%s+/oradata/ap ...

  5. CPU缓存一致性协议—MESI详解

    MESI(也称伊利诺斯协议)是一种广泛使用的支持写回策略的缓存一致性协议,该协议被应用在Intel奔腾系列的CPU中. MESI协议中的状态 CPU中每个缓存行使用的4种状态进行标记(使用额外的两位b ...

  6. Kotlin中,lateinit 和 lazy{} 的区别

    1.lazy{} 只能用在val类型, lateinit 只能用在var类型 如 : val name: String by lazy { "sherlbon" }lateinit ...

  7. XLMHttpRequest对象的status属性,readyState属性以及onreadystatechange事件

    注:XLMHttpRequest简写为XHR 一.HTTP请求过程 (1)建立TCP链接 (2)web浏览器向web服务器发送请求命令 (3)web浏览器发送请求头信息 (4)web服务器应答 (5) ...

  8. Hadoop Streaming开发要点

    一.shell脚本中的相关配置 HADOOP_CMD="/usr/local/src/hadoop-1.2.1/bin/hadoop" STREAM_JAR_PATH=" ...

  9. Zookeeper学习笔记1

    参考:从Paxos到Zookeeper分布式一致性原理与实践 从ACID到CAP/BASE ACID 事务(Transaction),一般是指要做的或所做的事情.在计算机术语中是指访问并可能更新数据库 ...

  10. go byte 和 string 类型之间转换

    string 不能直接和byte数组转换 string可以和byte的切片转换 1,string 转为[]byte var str string = "test" var data ...