`
cyhcheng
  • 浏览: 58353 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Web Socket入门

    博客分类:
  • web
 
阅读更多

最近对html5产生了兴趣,所以花了点心思在这方面,基于JBoss Netty写了个简单的web socket应用,主要拷贝了Netty的官方范例代码,如果想深入了解的话,最好还是好好看看Java NIO及Netty。

服务器端代码:
1、创建一个简单的管道实现:

package org.penguin.study.nettty.http.websocket;

import static org.jboss.netty.channel.Channels.pipeline;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;

public class WebSocketServerPipelineFactory implements ChannelPipelineFactory {
	public ChannelPipeline getPipeline() throws Exception {
		// Create a default pipeline implementation.
		ChannelPipeline pipeline = pipeline();
		pipeline.addLast("decoder", new HttpRequestDecoder());
		pipeline.addLast("aggregator", new HttpChunkAggregator(65536));
		pipeline.addLast("encoder", new HttpResponseEncoder());
		pipeline.addLast("handler", new WebSocketServerHandler());
		return pipeline;
	}
}

 2、 请求处理,可是最重要的一部分,核心代码尽在于此:

package org.penguin.study.nettty.http.websocket;

import static org.jboss.netty.handler.codec.http.HttpHeaders.*;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Values.*;
import static org.jboss.netty.handler.codec.http.HttpMethod.*;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*;
import static org.jboss.netty.handler.codec.http.HttpVersion.*;

import java.security.MessageDigest;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.HttpHeaders.Names;
import org.jboss.netty.handler.codec.http.HttpHeaders.Values;
import org.jboss.netty.handler.codec.http.websocket.DefaultWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocket.WebSocketFrame;
import org.jboss.netty.handler.codec.http.websocket.WebSocketFrameDecoder;
import org.jboss.netty.handler.codec.http.websocket.WebSocketFrameEncoder;
import org.jboss.netty.util.CharsetUtil;

public class WebSocketServerHandler extends SimpleChannelUpstreamHandler {

	private static final String WEBSOCKET_PATH = "/websocket";

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		Object msg = e.getMessage();
		if (msg instanceof HttpRequest) {
			handleHttpRequest(ctx, (HttpRequest) msg);
		} else if (msg instanceof WebSocketFrame) {
			handleWebSocketFrame(ctx, (WebSocketFrame) msg);
		}
	}

	private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
		// Serve the WebSocket handshake request.
		if (req.getUri().equals(WEBSOCKET_PATH) && Values.UPGRADE.equalsIgnoreCase(req.getHeader(CONNECTION))
				&& WEBSOCKET.equalsIgnoreCase(req.getHeader(Names.UPGRADE))) {

			// Create the WebSocket handshake response.
			HttpResponse res = new DefaultHttpResponse(HTTP_1_1, new HttpResponseStatus(101, "Web Socket Protocol Handshake"));
			res.addHeader(Names.UPGRADE, WEBSOCKET);
			res.addHeader(CONNECTION, Values.UPGRADE);

			// Fill in the headers and contents depending on handshake method.
			if (req.containsHeader(SEC_WEBSOCKET_KEY1) && req.containsHeader(SEC_WEBSOCKET_KEY2)) {
				// New handshake method with a challenge:
				res.addHeader(SEC_WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
				res.addHeader(SEC_WEBSOCKET_LOCATION, getWebSocketLocation(req));
				String protocol = req.getHeader(SEC_WEBSOCKET_PROTOCOL);
				if (protocol != null) {
					res.addHeader(SEC_WEBSOCKET_PROTOCOL, protocol);
				}

				// Calculate the answer of the challenge.
				String key1 = req.getHeader(SEC_WEBSOCKET_KEY1);
				String key2 = req.getHeader(SEC_WEBSOCKET_KEY2);
				int a = (int) (Long.parseLong(key1.replaceAll("[^0-9]", "")) / key1.replaceAll("[^ ]", "").length());
				int b = (int) (Long.parseLong(key2.replaceAll("[^0-9]", "")) / key2.replaceAll("[^ ]", "").length());
				long c = req.getContent().readLong();
				ChannelBuffer input = ChannelBuffers.buffer(16);
				input.writeInt(a);
				input.writeInt(b);
				input.writeLong(c);
				
				ChannelBuffer output = ChannelBuffers.wrappedBuffer(MessageDigest.getInstance("MD5").digest(	input.array()));
				res.setContent(output);
			} else {				
				res.addHeader(WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
				res.addHeader(WEBSOCKET_LOCATION, getWebSocketLocation(req));
				String protocol = req.getHeader(WEBSOCKET_PROTOCOL);
				if (protocol != null) {
					res.addHeader(WEBSOCKET_PROTOCOL, protocol);
				}
			}

			// Upgrade the connection and send the handshake response.
			ChannelPipeline p = ctx.getChannel().getPipeline();
			p.remove("aggregator");
			p.replace("decoder", "wsdecoder", new WebSocketFrameDecoder());

			ctx.getChannel().write(res);

			p.replace("encoder", "wsencoder", new WebSocketFrameEncoder());
			return;
		}

		// Send an error page otherwise.
		sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN));
	}
	private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
		// 发送消息回执
                                ctx.getChannel().write(new DefaultWebSocketFrame("动拐动拐,我是动爻,消息已收到:" + frame.getTextData()));
	}

	private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
		// Generate an error page if response status code is not OK (200).
		if (res.getStatus().getCode() != 200) {
			res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
			setContentLength(res, res.getContent().readableBytes());
		}
		// Send the response and close the connection if necessary.
		ChannelFuture f = ctx.getChannel().write(res);
		if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
			f.addListener(ChannelFutureListener.CLOSE);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		System.err.println("出现错误:" + e.getCause().getMessage());
		e.getChannel().close();
	}

	private String getWebSocketLocation(HttpRequest req) {
		return "ws://" + req.getHeader(HttpHeaders.Names.HOST) + WEBSOCKET_PATH;
	}
}

 3、服务器代码:

package org.penguin.study.nettty.http.websocket;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

public class WebSocketServer {
	public static void main(String[] args) {
		// Configure the server.
		ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
				Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

		// Set up the event pipeline factory.
		bootstrap.setPipelineFactory(new WebSocketServerPipelineFactory());

		// Bind and start to accept incoming connections.
		bootstrap.bind(new InetSocketAddress(8888));
	}
}

 4、测试的浏览器代码,在Google Chrome下测试正常运行,IE、Firefox、360目前不支持Web Socket。

写道
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Web Socket范例</title>
<script type="text/javascript">
var socket;
if (window.WebSocket) {
socket = new WebSocket("ws://WebSocket服务器地址:8888/websocket");
socket.onmessage = function(event) { alert(event.data); };
socket.onopen = function(event) { alert("Web Socket成功链接!"); };
socket.onclose = function(event) { alert("Web Socket已被关闭!"); };
} else {
alert("对不起,您的浏览器不支持Web Socket,目前建议使用新版的Chrome浏览器!");
}

function send(message) {
if (!window.WebSocket) { return; }
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
} else {
alert("没有打开Socket,请检查网络及服务器是否正常运行!");
}
}
</script>

</head>

<body>
<form onsubmit="return false;">
<input type="text" name="message" value="动爻动爻,我是动拐"/><input type="button" value="发送" onclick="send(this.form.message.value)" />
</form>

</body>
</html>

 

分享到:
评论
1 楼 穷土包 2011-12-21  
CONNECTION是那个类里的常量啊?

相关推荐

    简单 web socket实例

    这是一个简单的实例,在eclipse中打开,适合入门的使用,复杂的功能需要自己开发

    Linuxsocket编程入门[参照].pdf

    Linux Socket 编程入门 Linux Socket 编程入门是指在 Linux 操作系统中使用 Socket 编程技术来实现网络通信的过程。Socket 编程是网络编程的基础,是实现网络通信的核心技术。本教程将从基础开始,详细介绍 Linux ...

    java NIO socket聊天室

    可以作为NIO socket入门的例子,Reactor模式,重点理解key.attach, jar文件里包含了源代码 1,运行server.bat启动服务器,可以打开编辑,修改端口号 2,运行client.bat启动客户端,可以打开编辑,ip,和端口号 3...

    C# SuperSocket 手把手教你入门 傻瓜教程-2(服务器和客户端双向通信).zip

    让不懂SuperSOCKET的初学人员可以快速(只花几分钟的功夫)搭建自己的简易服务器。先从大方向讲解要做哪些基础工作(下载哪些组件,组件该如何配置),然后叙述要编写哪几步逻辑等等,方便初学者掌握大方向该如何...

    web_socket

    web_socket 一个新的Flutter应用程序。入门该项目是Flutter应用程序的起点。 如果这是您的第一个Flutter项目,那么有一些资源可以帮助您入门:要获得Flutter入门方面的帮助,请查看我们的,其中提供了教程,示例,...

    10.Python实战操作源码Web开发.zip

    01如何生成包含字母和数字的图片验证码02如何检测输入的图片验证码是否正确. ...17利用Channels实现Web Socket聊天室.18自定义django-admin命令 19 如何实现message消息提示.20使用Paginator实现数据分页.21 利用

    (完整word版)HTML5+CSS3从入门到精通自测练习.doc

    11. Web Socket: Web Socket是HTML5中一种实时通信机制,可以实现实时数据传输和推送。 12. CSS3选择器: CSS3选择器可以选择HTML文档中的元素,可以选择id、class、tag、attribute等。 13. CSS3样式: CSS3...

    python基础入门教程 基础进阶教程 共155页.pdf

    * 利用 Python SOCKET 多线程开发 FTP 视频课程 * 老男孩高薪必备 Python 高级运维编程实战课程 * 如何用 Python 快速开发出高大上运维管理平台实战课程 通过本教程,读者可以系统地学习Python语言,掌握核心技术和...

    webrtc初学者的入门示例应用

    webrtc初学者的入门示例应用,包括基于socket.io的简单信号服务器,以及Web / Android / iOS / Windows平台上的一些客户端演示。

    docker-ui:一个Web界面,用于通过Socket.IO和NodeJs列出并显示来自Docker的容器日志

    docker-ui 一个Web界面,用于列出和显示来自Docker的容器日志,从而保持Socket.IO和NodeJ的实时体验。入门列出容器将此存储库克隆到您的Docker服务器计算机上; 运行节点server.js并访问列出您的容器。记录容器在...

    QuickStart-Gatling:Gatling 测试的快速入门

    它可以用作负载测试工具,用于分析和测量各种服务的性能,重点是 Web 应用程序。 Gatling 官方支持以下协议:HTTP、WebSockets、Server Sent Events 和 JMS。 模拟是代码,多亏了用户友好的 DSL。 这允许用户通过...

    精品课件 Python从入门到精通 第19章 网络编程(共11页).pptx

    【完整Python从入门到精通课件如下】 Python从入门到精通 第1章 走进Python.ppt ...Python从入门到精通 第20章 Web编程.pptx Python从入门到精通 第21章 Flask框架.pptx Python从入门到精通 第22章 e起去旅行网站.pptx

    Node.js入门经典

    《Node.js入门经典》分为6部分,第1部分介绍了Node.js的基本概念和特性;第2部分讲解如何借助HTTP模块和Express Web框架,使用Node.js创建基本的网站;第3部分介绍了调试和测试Node.js应用程序的工具,以及部署Node....

    使用React + Redux + Socket.io + Material-UI实现聊天室-JavaScript开发

    演示功能:显示在线用户更改消息框颜色保留聊天室/清除消息入门要执行p聊天室,请使用React + Redux + Socket.io + Material-UI实现聊天室。 演示功能:显示在线用户更改消息框颜色保留聊天室/清除消息入门要执行该...

    .NET常用源代码

    web api入门用的例子程序 web api的crud操作 ajax方式实现的聊天室 cms管理员后台模板 条码扫描 winforms实现用户登录逻辑 socket通讯的例子 将gridview导出到 word excel ppt pdf等文档 将excel转换为xml 修改并且...

    node.js入门经典

    《Node.js入门经典》分为6部分,第1部分介绍了Node.js的基本概念和特性;第2部分讲解如何借助HTTP模块和Express Web框架,使用Node.js创建基本的网站;第3部分介绍了调试和测试Node.js应用程序的工具,以及部署Node....

    SSL、TLS协议格式入门学习

    SSL、TLS协议格式入门学习 SSL(Secure socket Layer 安全套接层协议)指使用公钥和私钥技术组合的安全网络通讯协议。SSL协议是网景公司(Netscape)推出的至于WEB应用 的安全协议,SSL协议指定了一种在应用程序协议...

    Vue全家桶 + Koa+Socket+Vant前后端分离移动端聊天应用。vue+node全栈入门项目.zip

    软件开发设计:应用软件开发、系统软件开发、移动应用开发、网站开发C++、Java、python、web、C#等语言的项目开发与学习资料 硬件与设备:单片机、EDA、proteus、RTOS、包括计算机硬件、服务器、网络设备、存储设备...

    react-socket-io:使用socket.io在React和Node中创建的基本聊天应用程序。 :winking_face::winking_face:

    ReactSocket.io 我已经创建了一个聊天应用程序,它使用React和Node以及帮助socket.io来实现Web套接字。 该项目用于理解以React为前端,Node为后端的socket.io的目的。 该项目的目标是学习有关socket.io的基本概念...

    Python基础入门到精通 .pdf

    * 使用 Python SOCKET 多线程开发 FTP 软件。 * TriAquae 快速上手教程。 4. 版本控制: * 使用 Git 对 Python 代码进行版本控制。 5. 高级运维编程: * 使用 Python 高级运维编程实现精品入门进阶。 6. Web ...

Global site tag (gtag.js) - Google Analytics