(2)Netty项目——简易消息通讯

  一、回顾

创建一个简单的netty项目server/client_ZHY_ERIC的博客-CSDN博客一、环境JDK1.8eclipsenettyhttps://mvnrepository.com/artifact/io.netty/netty-all/4.1.75.Final二、新建一个maven项目 打开eclipse:选择项目类型项目创建成功:三、配置pom.xml文件https://mvnrepository.com/artifact/io.netty/...https://blog.csdn.net/ZHY_ERIC/article/details/123987102        上一篇中,我们用netty搭建了一个建议的server/client。


 二、创建项目

       学习完第一篇,下面继续做一个简易的消息通讯功能。

        新建一个websocket的package。

        完整的项目组织架构:

三、创建WSServer.java文件

package com.netty.websocket;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class WSServer {
	
	public static void main(String[] args) throws Exception {
		//	定义一对线程组
		//	主线程组,用于接受客户端的连接,但是不做任何处理,跟老板一样,不做事
		EventLoopGroup mainGroup = new NioEventLoopGroup();
		//	从线程组,老板线程组会把任务丢给他,让手下线程组去做任务
		EventLoopGroup subGroup = new NioEventLoopGroup();
		
		
		try {
			//	netty服务器的创建,ServerBootstrap是一个启动类
			ServerBootstrap server = new ServerBootstrap();
			server.group(mainGroup,subGroup)			//	设置主从线程组
				.channel(NioServerSocketChannel.class)	//	设置nio的双向通道
				.childHandler(new WSServerInitialzer());	//	子处理器,用于处理workerGroup
			
			//	启动server,并且设置8089为启动的端口号,同时设置启动方式为同步
			ChannelFuture future = server.bind(8089).sync();
			//	监听关闭的channel,设置为同步方式
			future.channel().closeFuture().sync();
		} finally {
			mainGroup.shutdownGracefully();
			subGroup.shutdownGracefully();
		} 
	}

}

四、WSServerInitialzer.java文件

package com.netty.websocket;


import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WSServerInitialzer extends ChannelInitializer<SocketChannel>{

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		// TODO Auto-generated method stub
		ChannelPipeline pipeline = ch.pipeline();
		
		// websocket 基于http协议,所以要有http编解码器
		pipeline.addLast(new HttpServerCodec());
		// 对写大数据流的支持
		pipeline.addLast(new ChunkedWriteHandler());
		//	对httpMessage进行聚合,聚合成FullHttpRequest或FullHttpResponse
		//	几乎在netty中的编程,都会使用到此handler
		pipeline.addLast(new HttpObjectAggregator(1024*64));
		
		//============================以上是用于支持http协议========================
		
		/**
		 * 	websocket服务器处理的协议,用于指定给客户端连接访问的路由: /ws
		 * 	本handler会帮你处理一些繁重的复杂的事情
		 * 	会帮你处理握手动作: handshaking(close, ping, pong) ping + pong =心跳
		 * 	对于websocket来讲,都是以frames进行传输的,不同的数据类型对应的frames也不同
		 */
		pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
		
		//	自定义handler
		pipeline.addLast(new ChatHandler());
	}


}

五、创建ChatHandler .java文件

package com.netty.websocket;

import java.time.LocalDateTime;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;



/**
 * 
 * @author 14415
 * TextWebSocketFrame:在netty中,是用于为websocket专门处理文本的对象,frame是消息的载体
 *
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	
	// 用于记录和管理所有的客户端
	private static ChannelGroup clients = 
			new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) 
			throws Exception {
		// 获取客户端传输过来的消息
		String content = msg.text();
		System.out.println("接收到的数据:" + content);
		
		for(Channel channel:clients) {
			channel.writeAndFlush(
					new TextWebSocketFrame(
							"[服务器在]" + LocalDateTime.now() 
							+ ",接受到消息为:" + content));
		}
		// 下面这个方法,和上面的for循环一致
//		clients.writeAndFlush(
//				new TextWebSocketFrame(
//						"[服务器在]" + LocalDateTime.now() 
//						+ ",接受到消息为:" + content));
	}
	
	/**
	 * 当客户端连接服务器之后(打开连接)
	 * 获取客户端的channel,并且放到Channelgroup中去进行管理
	 */

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		
		clients.add(ctx.channel());
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		// 当触发handlerRemoved, ChannelGroup会自动移除对应客户端的channel
//		clients.remove(ctx.channel());
		System.out.println("客户端断开,Channel对应的长id为:" 
				+ ctx.channel().id().asLongText());
		System.out.println("客户端断开,Channel对应的短id为:"
				+ ctx.channel().id().asShortText());
	}

}

 六、创建pom.xml文件

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.test.netty</groupId>
  <artifactId>netty.hello</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
   <dependencies>
 	<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
	<dependency>
	    <groupId>io.netty</groupId>
	    <artifactId>netty-all</artifactId>
	    <version>4.1.75.Final</version>
	</dependency>
  </dependencies>
</project>

 七、前端代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title></title>
</head>
<body>
	<div>发送消息:</div>
	<input type="text" id="msgContent"/>
	<input type="button" value="点我发送" onclick="CHAT.chat()"/>
	
	<div>接受消息:</div>
	<div id="receiveMsg" style="background-color: #0086B3;"></div>
	<script type="text/javascript" charset="utf-8">
	  	window.CHAT = {
			socket:null,
			init: function(){
				if(window.WebSocket){
					CHAT.socket = new WebSocket("ws://192.168.1.106:8089/ws");
					CHAT.socket.onopen = function(){
						console.log("连接建立成功...");
					},
					CHAT.socket.onclose = function(){
						console.log("连接关闭...");
					},
					CHAT.socket.onerror = function(){
						console.log("连接错误...");
					},
					CHAT.socket.onmessage = function(e){
						console.log("接受到消息:"+e.data);
						var receiveMsg = document.getElementById("receiveMsg");
						var html = receiveMsg.innerHTML;
						receiveMsg.innerHTML = html + "<br/>" + e.data;
					}
				}   else{
					alert("浏览器不支持websocket协议....");
				}
			},
			chat: function(){
				var msg = document.getElementById("msgContent");
				CHAT.socket.send(msg.value);
			}
		};
		CHAT.init();
	</script>
</body>
</html>

 八、执行效果

        首先启动后端程序:我这里开放的是本地的8089端口:

        在浏览器打开我们的前端html文件,我这里是google浏览器。进入开发者模式

         这是,我们在前端输入,hello friend!!!,单击发送。

        前端效果:

           后端效果: 

   九、源代码
ZHY_ERIC / netty-hello-v2 · GitCodeGitCode——开源代码托管平台,独立第三方开源社区,Git/Github/Gitlabhttps://gitcode.net/ZHY_ERIC/netty-hello-v2

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值