Netty5+Websocket

根据官方文档和自己实际操作整理,方便自己以后使用。为了方便,用maven做的例子。


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 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Socket</groupId>
  <artifactId>S</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>S Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- netty -->
	<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>5.0.0.Alpha1</version>
</dependency>


	<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>
	<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.4</version>
</dependency>
  </dependencies>
  <build>
    <finalName>S</finalName>
  </build>
</project>

NettyServer.java

package websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class NettyServer implements ServletContextListener {  
      
	public static void main(String[] args) {
		new NettyServer().run();
	}
    public void run(){  
	   	  //boss
	       EventLoopGroup bossGroup = new NioEventLoopGroup();  
	       	//worker
	       EventLoopGroup workGroup = new NioEventLoopGroup();  
	         
	       try {  
	           ServerBootstrap b = new ServerBootstrap();  
	           b.group(bossGroup, workGroup);
	           b.channel(NioServerSocketChannel.class);  
	           b.childHandler(new ChannelInitializer<SocketChannel>() {  
	           	  
	   			protected void initChannel(SocketChannel e) throws Exception {
	   					e.pipeline().addLast("http-codec",new HttpServerCodec());
	         	        e.pipeline().addLast("aggregator",new HttpObjectAggregator(65536));  
	         	        e.pipeline().addLast("http-chunked",new ChunkedWriteHandler());  
	         	        e.pipeline().addLast("handler",new MyWebSocketServerHandler());  
	   			}
	   			
	           });  
	           // Start the server.
	           Channel ch = b.bind(8082).sync().channel();  
	           // Wait until the server socket is closed.
	           ch.closeFuture().sync();  
	             
	       } catch (Exception e) {  
	           e.printStackTrace();  
	       }finally{ 
	       	// Shut down all event loops to terminate all threads.
	           bossGroup.shutdownGracefully();  
	           workGroup.shutdownGracefully();  
	       }  
	         
	   }

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		 System.err.println("nettyListener Startup!");  
	        new Thread(){  
	            @Override  
	            public  void run(){  
	                try {  
	                    new NettyServer().run();  
	                } catch (Exception e) {  
	                    e.printStackTrace();  
	                }  
	            }  
	        }.start();  
	      
	        System.err.println("nettyListener end!");  
		
	}  
      
}   

NettyServer类实现了ServletContextListener,通过listener来启动netty服务。(暂时未做将netty服务配置到spring中)


Global.java

package websocket;

import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class Global {
	public static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}

MyWebSocketServerHandler.java

package websocket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
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.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;


public class MyWebSocketServerHandler extends
		SimpleChannelInboundHandler<Object> {
	private static final Logger logger = Logger
			.getLogger(WebSocketServerHandshaker.class.getName());
	private WebSocketServerHandshaker handshaker;
	public static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);  

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// 添加
		group.add(ctx.channel());
		System.out.println("客户端与服务端连接开启");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// 移除
	group.remove(ctx.channel());
		System.out.println("客户端与服务端连接关闭");
	}

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		if (msg instanceof FullHttpRequest) {
			handleHttpRequest(ctx, ((FullHttpRequest) msg));
		} else if (msg instanceof WebSocketFrame) {
			handlerWebSocketFrame(ctx, (WebSocketFrame) msg);
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	private void handlerWebSocketFrame(ChannelHandlerContext ctx,
			WebSocketFrame frame) {
		// 判断是否关闭链路的指令
		if (frame instanceof CloseWebSocketFrame) {
			handshaker.close(ctx.channel(),
					(CloseWebSocketFrame) frame.retain());
		}
		// 判断是否ping消息
		if (frame instanceof PingWebSocketFrame) {
			ctx.channel().write(
					new PongWebSocketFrame(frame.content().retain()));
			return;
		}
		// 本例程仅支持文本消息,不支持二进制消息
		if (!(frame instanceof TextWebSocketFrame)) {
			System.out.println("本例程仅支持文本消息,不支持二进制消息");
			throw new UnsupportedOperationException(String.format(
					"%s frame types not supported", frame.getClass().getName()));
		}
		// 返回应答消息
		String request = ((TextWebSocketFrame) frame).text();
		
		
		
		String news = "4564";
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", "123456");
		
		System.out.println("服务端收到:" + request);
		if (logger.isLoggable(Level.FINE)) {
			logger.fine(String.format("%s received %s", ctx.channel(), request));
		}
		TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString()
				+ ctx.channel().id() + ":" +news+map);
		// 群发
		group.writeAndFlush(tws);
		// 返回【谁发的发给谁】
		// ctx.channel().writeAndFlush(tws);
	}
	private void handleHttpRequest(ChannelHandlerContext ctx,
			FullHttpRequest req) {
		if (!req.getDecoderResult().isSuccess()
				|| (!"websocket".equals(req.headers().get("Upgrade")))) {
			sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
					HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
			return;
		}
		WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
				"ws://localhost:8082/websocket", null, false);
		handshaker = wsFactory.newHandshaker(req);
		if (handshaker == null) {
			WebSocketServerHandshakerFactory
					.sendUnsupportedWebSocketVersionResponse(ctx.channel());
		} else {
			handshaker.handshake(ctx.channel(), req);
		}
	}

	private static void sendHttpResponse(ChannelHandlerContext ctx,
			FullHttpRequest req, DefaultFullHttpResponse res) {
		// 返回应答给客户端
		if (res.getStatus().code() != 200) {
			ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
					CharsetUtil.UTF_8);
			res.content().writeBytes(buf);
			buf.release();
		}
		// 如果是非Keep-Alive,关闭连接
		ChannelFuture f = ctx.channel().writeAndFlush(res);
		if (!isKeepAlive(req) || res.getStatus().code() != 200) {
			f.addListener(ChannelFutureListener.CLOSE);
		}
	}

	private static boolean isKeepAlive(FullHttpRequest req) {
		return false;
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <javaee:display-name>Archetype Created Web Application</javaee:display-name>
  <listener>  
        <listener-class>websocket.NettyServer</listener-class>  
    </listener> 
</web-app>

html

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<script type="text/javascript">
		var socket;
		if(!window.WebSocket) {
			window.WebSocket = window.MozWebSocket;
		}
		if(window.WebSocket) { 
			socket = new WebSocket("ws://localhost:8082/websocket");
			socket.onmessage = function(event) {
				var ta = document.getElementById('responseText');
				ta.value += event.data + "\r\n";
			};
			socket.onopen = function(event) {
				var ta = document.getElementById('responseText');
				ta.value = "打开WebSoket 服务正常,浏览器支持WebSoket!" + "\r\n";
			};
			socket.onclose = function(event) {
				var ta = document.getElementById('responseText');
				ta.value = "";
				ta.value = "WebSocket 关闭" + "\r\n";
			};
		} else {
			alert("您的浏览器不支持WebSocket协议!");
		}

		function closeweb() {
			alert("www");
			socket.onclose;
		}

		function send() {
			var message = document.getElementById('msg').value;
			if(!window.WebSocket) {
				return;
			}
			if(socket.readyState == WebSocket.OPEN) {
				socket.send(message);
			} else {
				alert("WebSocket 连接没有建立成功!");
			}
		}
	</script>

	<body>
		<form onsubmit="return false;"> <textarea type="text" id="msg" name="message" value="" style="width: 1000px;height: 90px;">
			
		</textarea> <br/><br/> <input type="button" value="发送 WebSocket 请求消息" onclick="send()" />
			<input type="button" value="关闭" onclick="closeweb()" />
			<hr color="blue" />
			<h3>服务端返回的应答消息</h3> <textarea id="responseText" style="width: 1024px;height: 300px;"></textarea>
		</form>
	</body>

</html>

这是一个简单的通信例子是通过group群发的,也可以通过channel.writeAndFlush()实现单一转发,但在一次通信的过程中,只能对一个channel进行消息的转发。在netty5中无法通过遍历Map实现群发。如果要实现定向的群发,可以遍历map加入到group中,然后实现群发,不会出错。 

Map<ChannelId, Channel> map = new ConcurrentHashMap<ChannelId, Channel>();
ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
                              for (Channel ch : map.values()) {
					group.add(ch);
				}
				group.writeAndFlush(tw);
				for (Channel ch : map.values()) {
					group.remove(ch);
				}


猜你喜欢

转载自blog.csdn.net/HGJacky/article/details/79663978
今日推荐