Netty实现WebSocket

HTTP协议,快速简单、灵活、无连接、无状态,同时具有如下弊端:

1> HTTP协议是半双工的协议,半双工协议是指可以在客户端和服务端两个方向上传输,但不能同时传输。这意味着同一时刻只有一个方向上的数据传输。

2> HTTP消息冗长而繁琐,包括消息头、消息体、换行符等。通常情况下采用文本方式传输,相比其他二进制的通信协议,冗长而繁琐。

3> 针对于服务器推送的黑客攻击,如长时间轮询,浏览器不断向服务器发出请求,然而HTTP request的Header是非常冗长的,里面包含的可用数据比例可能非常低,这会占用很多带宽资源和服务器资源。

附: HTTP1.1与HTTP1.0的比较: http://www.voidcn.com/blog/elifefly/article/p-1180220.html

Websocket,是一种浏览器与服务器进行全双工通信的网络协议,是HTML5中最让人兴奋的功能特性之一。在websocket API中,浏览器和服务器只需要做一个握手的动作,两者形成了一条快速通道,可以直接相互传送数据。具有以下特点:

1> 单一的TCP连接,采用全双工模式通信。

2> 无头部信息、cookie和身份验证

3> 无安全开销

4> 服务器可以主动传递消息给客户端,不需要客户端轮询

连接建立

通过HTTP协议建立握手连接,在接连建立后,真正的数据传输阶段是不需要HTTP协议参与的。典型的WebSocket握手如下:


这段HTTP请求较之普通的HTTP,多了Connection:UpgradeUpgrade:websocket两个Request Header,表明这是一个升级版的HTTP——WebSocket

Sec-WebSocket-Key是一个base64 encode值,这个是浏览器随机生成的,服务器会根据这些数据构造一个SHA-1的信息摘要,将其值放入sec-websocket-accept中返回给客户端。服务器返回如上图Response Headers所示。表示成功建立Socket啦。

连接关闭

客户端和服务端通过一个安全的方法关闭底层TCP连接和TLS会话。底层的TCP连接,在正常情况下,应该首先由服务器关闭,异常情况下客户端可以发起TCP Close。当服务器被指使关闭websocket连接时,它应该立即发起一个TCP Close,客户端应等待服务器的TCP Close。


目前主流浏览器如Chrome、FireFox、IE10、Opera10、Safari等都已经支持WebSocket,服务端也出现了一些不错的WebSocket项目如Netty、Resin、Jetty7、pywebsocket等。下面的例子,通过Netty实现WebSocket服务端,用JavaScript实现WebSocket客户端。

WebSocket服务端

package demo.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
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.stream.ChunkedWriteHandler;

public class WebSocketServer {

	private final EventLoopGroup workerGroup = new NioEventLoopGroup();
	private final EventLoopGroup bossGroup = new NioEventLoopGroup();

	public void run() {

		ServerBootstrap boot = new ServerBootstrap();

		boot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
				.childHandler(new ChannelInitializer<Channel>() {

					protected void initChannel(Channel ch) throws Exception {

						ChannelPipeline pipeline = ch.pipeline();
						// 将请求和应答的消息编码或者解码为HTTP消息
						pipeline.addLast("http-codec", new HttpServerCodec());
						// 将HTTP消息的多个部分组合成一条完整的HTTP消息
						pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
						// 向客户端发送HTML5文件,主要用于支持浏览器和服务端进行websocket通信
						pipeline.addLast("http-chunked", new ChunkedWriteHandler());
						// 消息的Handler处理类
						pipeline.addLast("handler", new WebSocketServerHandler());
					}
				});

		try {
			// 绑定端口来接受连接
			ChannelFuture f = boot.bind(2048).sync();
			System.out.println("websocket server start at port: 2048");
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {

			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	
	/**
	 * Main函数 
	 */
	public static void main(String[] args) {

		new WebSocketServer().run();
	}
}

package demo.websocket;

import java.util.List;
import java.util.Map.Entry;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
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;

public class WebSocketServerHandler extends ChannelHandlerAdapter {

	private WebSocketServerHandshaker handshaker;

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		
		// HTTP接入,WebSocket第一次连接使用HTTP连接,用于握手 
		// HTTP握手完成后,才是WebSocket下的通信
		if (msg instanceof FullHttpRequest) {

			handleHttpRequest(ctx, (FullHttpRequest) msg);

		} 
		// Websocket 接入
		else if (msg instanceof WebSocketFrame) {

			handleWebSocketFrame(ctx, (WebSocketFrame) msg);
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

		ctx.close();
	}

	private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
		
		HttpHeaders headers = req.headers();
		List<Entry<CharSequence, CharSequence>> list = headers.entries();
		for(Entry<CharSequence, CharSequence> entity : list){
			
			System.out.println("header " + entity.getKey() + ": " + entity.getValue());
		}
		
		// WebSocket 通过"Upgrade handshake(升级握手)"从标准的 HTTP 或HTTPS 协议转为 WebSocket
		// 屏蔽掉 不是 WebSocket握手的请求
		if (!req.decoderResult().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:2048/ws",
				null, false);
		handshaker = wsFactory.newHandshaker(req);
		// 无法处理的WebSocket版本
		if (handshaker == null) {

			WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
		} else {
			// 向客户端发送WebSocket握手,完成握手
			// 客户端收到的status是101 Switching Protocols
			handshaker.handshake(ctx.channel(), req);
		}
	}

	private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, DefaultFullHttpResponse res) {
		
		// 返回应答给客户端
		if (res.status().code() != 200) {

			ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
			res.content().writeBytes(buf);
			buf.release();
		}

		// 如果是非Keep-Alive,关闭连接
		ChannelFuture f = ctx.channel().writeAndFlush(res);
		if (!isKeepAlive(req) || res.status().code() != 200) {

			f.addListener(ChannelFutureListener.CLOSE);
		}
	}

	private static boolean isKeepAlive(FullHttpRequest req) {

		return false;
	}

	private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

		// 判断是否关闭链路的指令
		if (frame instanceof CloseWebSocketFrame) {

			handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());

			return;
		}
		
		// 判断是否ping消息
		if (frame instanceof PingWebSocketFrame) {

			ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
			return;
		}

		// 本例程不支持二进制消息
		if (frame instanceof BinaryWebSocketFrame) {

			throw new UnsupportedOperationException(
					String.format("%s frame types not supported", frame.getClass().getName()));
		}

		// 文本消息
		if (frame instanceof TextWebSocketFrame) {

			// 返回应答消息
			String request = ((TextWebSocketFrame) frame).text();
			System.out.println("服务端收到: " + request);
			ctx.channel().write(new TextWebSocketFrame("服务器收到并返回:" + request));
		}
	}
}

JavaScript客户端 websocket.html



运行Main方法,启动服务端,打开websocket.html,试一下效果。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值