在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
一、首先,需要了解一下websocket基本原理:here 二、go语言的websocket实现: 基于go语言的websocket也有不少,比如github.com/gorilla/websocket。这里选用的应该算是官方的实现code.google.com/p/go.net/websocket 使用go get安装下载即可。(不过,由于周知的原因:(,我是通过golangtc.com的第三方包下载功能才下载来的) 三、server端 第一个遇到的问题,websocket如何和martini集成? 安装websocket的文档,和http服务集成,应该使用如下方式 func ChatService (ws *websocket.Conn) { for{ 但是,如果注册到martini的route,运行时会报错 m.Any("/chat", websocket.Handler(ChatService))
经阅读Server.go代码,发现,需要使用websocket.Handler的方法ServeHTTP来注册(ps:因为websoket.Handler是个函数签名的自定义类型,所以,我们把ChatService转为websocket.Handler之后,就拥有了它的方法) m.Any("/chat", websocket.Handler(ChatService).ServeHTTP) 服务端代码,基于某些原因,这里贴上部分代码,其余请大家根据框架自己很容易实现: type chatMsg struct {
From string `json:"from"` 几点说明: 1如果读写数据遇到错误,甭犹豫,关掉连接; 上面第四点,应该是websocket服务缺少什么协议的实现,但是我没看出来,下面是调试信息,有知者望不吝赐教: 2015/01/14 13:43:46 glog.go:169 [[info] [[ChatService] *websocket.ProtocolError when read socket. Request: Head: [map[Sec-Websocket-Key:[GH09xUWLdTOVB0u3RJdOgA==] User-Agent:[Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)] Cache-Control:[no-cache] Cookie:[my_session=MTQyMTIxNDE2MXxRdXBlSjlVeTR4SG9TVTFSYUJkN1FyMW1GU0c2U05XdjBEc0F0NXZSQnZSbE1BaVdKem51aE44TktZdWNaaUtfaVZBVmVONE9JY1JUcFU0MVliVkFxR3BnUi1LQ2F0RV82b1FxUE9jMXlIV3NGdlhfbWZiLTBSLTQySHFKNmJlVVZJSWlScmpGZXZLWmZuXzc4aXM5UEZQY2ZlRzF8CISa785vyuDilrrpQTg4IKLyiH-U12yGai4ah-ixbV8=] Origin:[http://192.168.5.92:8088] Connection:[Upgrade] Upgrade:[Websocket] Sec-Websocket-Version:[13] Dnt:[1]] Body:&struct { http.eofReaderWithWriteTo; io.Closer }{eofReaderWithWriteTo:http.eofReaderWithWriteTo{}, Closer:ioutil.nopCloser{Reader:io.Reader(nil)}}]]] 四、基于网页的client端实现:(客户端浏览器当然需要支持websocket协议,当前最新的浏览器基本都支持了,IE需要10以上) <!doctype html> <html> <head> <title>websocket</title> <style> #log{height: 300px;overflow-y: scroll;border: 1px solid #CCC;padding:0;} #signinpad{display:none;background-color:#99F} .r-msg{color:#111;} .s-msg{color:#090;} .msg-from{font-family:fangsong;} .chat-msg{padding-left:15px;} </style> <script type="text/javascript" src="/js/easyui-1.4.1/jquery.min.js" ></script> <script type="text/javascript"> var sock = null; var wsuri = "ws://192.168.5.92:8088/chat"; $(document).on("ready",function() { console.log("onload"); jQuery.fn.flash = function( size, duration ) { try{ var current = this.css( 'border-width' ); if(current=="")current="0px" current = parseInt(current) this.animate( { 'borderWidth': 5 }, duration / 2 ); this.animate( { 'borderWidth': current }, duration / 2 ); }catch(ex){ console.log(ex) } } $("#message").on("keydown",function(evt){if(evt.keyCode==13){send();}}) try{ conn(); }catch(ex){ console.log(ex); alert("连接websocket务器报错:"+ex); $("#btnsend").attr("disabled","disabled"); $("#message").attr("disabled","disabled"); $("#btngetusers").attr("disabled","disabled"); } }); function conn(){ sock = new WebSocket(wsuri); regevt(); } function regevt(){ sock.onopen = function() { console.log("connected to " + wsuri); loaduser(); } sock.onerror = function(e) { console.log(" error from connect " + e); } sock.onclose = function(e) { console.log("connection closed (" + e.code + ")"); console.log("reconnecting...."); setTimeout( conn,1000); } sock.onmessage = onMsg; } function onMsg(e) { console.log("message received: " + e.data); var msg = window.JSON.parse(e.data); if (msg.type=="" ||msg.type=="msg"){ appendMsg(msg.from,msg.msg); }else if (msg.type=="needsignin"){ alert("signin first,please!"); $("#signinpad").css("display","block"); $('#btnsignin').removeAttr("disabled") $('#user').focus(); $('#btnsignin').on("click",function(){ var user = $('#user').val(); var pass = $('#password').val(); if( user==""){ alert("user name cannot be blank!") $('#user').focus();return } if( pass==""){ alert("password cannot be blank!") $('#password').focus();return; } appendMsg("self","signining"); $('#btnsignin').attr("disabled","disabled") 全部评论
专题导读
热门推荐
热门话题
阅读排行榜
|
请发表评论