在传统的网页实现聊天室的方法是通过每隔一段时间请求服务器获取相关聊天信息来实现,然而html5带来的websocket功能改变这了这种方式.由于websocket在连接服务器后允许保持连接来进行数据交互,因此服务器可以主动地向客户端发送相应的数据.对于html5的处理只需要在连接创建完成后在websocket的receive事件中处理接收的数据即可.下面通过实现一个聊天室来体验一下服务器可以主动地向客户端发的功能.
- <!DOCTYPE html>
- <?php
- //echo $_GET[‘othername’];exit;
- if($_GET[‘myid’]==$_GET[‘otherid’])
- {
- echo “<script>
- alert(‘您不能和自己聊天’);
- window.close();
- </script>”;
- }
- ?>
- <html>
- <head>
- <meta http-equiv=“Content-Type” content=“text/html; charset=utf-8” />
- <title>网站在线聊天-客户在线交流工具</title>
- <input type=“hidden” id=“otherid”
- value=“<?php echo $_GET[‘otherid’]?>”>
- <input type=“hidden” id=“othername”
- value=“<?php echo $_GET[‘othername’]?>”>
- <input type=“hidden” id=“otherimg”
- value=“<?php echo $_GET[‘otherimg’];?>”>
- <input type=“hidden” id=“myid” value=“<?php echo $_GET[‘myid’];?>”>
- <input type=“hidden” id=“myname”
- value=“<?php echo $_GET[‘myname’];?>”>
- <input type=“hidden” id=“myimg”
- value=“<?php echo $_GET[‘myimg’];?>”>
- <!– 查询数据库 中所有otherid的发来的离线聊天内容–>
- <?php
- $conn=mysql_connect(“192.168.1.100”,“root”,“”) or die(‘连接失败:’ . mysql_error());
- if(!mysql_select_db(“strategy”,$conn))
- {echo (‘数据库选择失败:’ . mysql_error());}
- mysql_query(“set names utf8”);
- $oid = $_GET[‘otherid’];
- $mid = $_GET[‘myid’];
- //在聊天窗口中列出未读的聊天信息
- $query = mysql_query(“select * from gy_chatmessage where receiverid=$oid and senderid=$mid and isscan=2 order by id asc”);
- //查看是否浏览过,isscan=1
- $isscan = isset($_GET[‘isscan’]) ? intval($_GET[‘isscan’]):”;
- if(!empty($isscan))
- {
- $q= mysql_query(“update gy_chatmessage set isscan=1 where receiverid=$oid and senderid=$mid “);
- }
- ?>
- <!–html5 websocket 通信程序–>
- <script type=“text/javascript”>
- var ws = null;
- var s=”; var i=0;
- var name = document.getElementById(“myname”).value;
- //var myusername;
- function startServer() {
- // 设定WebSocket,注意协议是ws,请求是指向对应的WebSocketServlet的
- //var url = “ws://192.168.1.101:8080/websocket88/websocket/echoAnnotation”;
- //var url = “ws://192.168.1.101:8080/WebSocket/servlet/SocketServer”;
- //var url = “ws://192.168.1.101:8080/test123/websocket/echoAnnotation”;
- var url = “ws://192.168.1.109:8080/GLServer/websocket/echoAnnotation”;
- // 创建WebSocket实例,下面那个MozWebSocket是Firefox的实现
- if (‘WebSocket’ in window) {
- ws = new WebSocket(url);
- //alert(“new WebSocket”);
- } else if (‘MozWebSocket’ in window) {
- ws = new MozWebSocket(url);
- } else {
- alert(‘您好,您的浏览器版本较低,暂不支持websocket,无法使用在线聊天功能,建议升级或使用IE10、chrome、Firefox、Opera、Safari等主流浏览器’);
- window.close();
- return false;
- }
- // WebSocket握手完成,连接成功的回调
- // 有个疑问,按理说new WebSocket的时候就会开始连接了,如果在设置onopen以前连接成功,是否还会触发这个回调
- ws.onopen = function() {
- //alert(‘连接好了’);
- alert(mytime()+’,您已经和对方连接成功,点击确定后开始和对方聊天’);
- var otherid = document.getElementById(“otherid”).value;
- var othername = document.getElementById(“othername”).value;
- var otherimg = document.getElementById(“otherimg”).value;
- var myid = document.getElementById(“myid”).value;
- var myname = document.getElementById(“myname”).value;
- var myimg = document.getElementById(“myimg”).value;
- //alert(username);
- ws.send(myid+“#”+myname+“#”+myimg+“#”+otherid+“#”+othername+“#”+otherimg);
- };
- // 收到服务器发送的文本消息, event.data表示文本内容
- ws.onmessage = function(event) {
- if(!i==0)
- {
- //var i=”;
- // i= event.data;
- //i=i.fontcolor(#FF0033);
- //s = s +event.data+'<br/>’;
- //s = s+i+'<br/>’;
- s = s+'<span style=“color:red;”>’+event.data+'</span><br/>’;
- //alert(‘Receive message: ‘ + s);
- document.getElementById(“a”).innerHTML=s;
- }else{
- // name=event.data;
- i++;
- }
- };
- // 关闭WebSocket的回调
- ws.onclose = function() {
- //alert(‘服务器断线,本次聊天被终止!’);
- };
- }
- function sendMyMessage() {
- //判断输入的内容是否为空
- var textMessage = document.getElementById(‘textMessage’).value;
- if(textMessage==”)
- {
- alert(‘发送内容不能为空哦’);
- return false;
- }
- Date.prototype.format = function(format){
- var o = {
- “M+” : this.getMonth()+1, //month
- “d+” : this.getDate(), //day
- “h+” : this.getHours(), //hour
- “m+” : this.getMinutes(), //minute
- “s+” : this.getSeconds(), //second
- “q+” : Math.floor((this.getMonth()+3)/3), //quarter
- “S” : this.getMilliseconds() //millisecond
- }
- if(/(y+)/.test(format)) {
- format = format.replace(RegExp.$1, (this.getFullYear()+“”).substr(4 – RegExp.$1.length));
- }
- for(var k in o) {
- if(new RegExp(“(“+ k +“)”).test(format)) {
- format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : (“00”+ o[k]).substr((“”+ o[k]).length));
- }
- }
- return format;
- }
- var now = new Date();
- var t = now.format(“yyyy-MM-dd hh:mm:ss”);
- //alert(t);
- textMessage = name+’ ’+t+'<br/>’+’ ’+textMessage
- //alert(textMessage);
- s = s + textMessage+'<br/>’;
- document.getElementById(“a”).innerHTML=s;
- if(ws != null && textMessage != ”) {
- // 通过WebSocket想向服务器发送一个文本信息
- ws.send(textMessage);
- //清空当前textarea域的内容
- document.getElementById(“textMessage”).value=”;
- }
- }
- </script>
- </head>
- <body onLoad=“startServer()”>
- <div id=“header”
- style=“width: 100%; height: 30px; border: 1px solid #ccc; background: #FF6600; color: red”><span
- style=“color: #0066FF; margin-left: 10px; line-height: 30px;”>网站webim在线聊天</span></div>
- <p id=“a” style=“height: 320px; width: 690px; border: 1px solid #d2d2d2; overflow-y: scroll;”>
- <span style=“color: #0066FF; margin:10px; margin-bottom:0px; display:block”>欢迎使用网站在线聊天系统,如果对方不在线,您可以给他留言。</span><br/>
- <?php
- while($row = mysql_fetch_array($query))
- {
- //print_r($row);
- echo ‘  ’.$row[‘receiver’];
- echo ‘  ’.$row[‘createtime’];
- echo ‘<br>’;
- echo ‘<br/>‘.’  ’;
- echo $row[‘content’];
- echo ‘<br/><br/>’;
- }
- ?>
- </p>
- <div id=“mid_mid”><span style=“font-size:12px; color:#FF9900”>请在下面文本框里输入你想要聊天的内容,禁止输入#等无意义的字符和违法信息</span></div>
- <div class=“webim-body-content-textarea”>
- <input id=“textMessage”
- size=“60” name=“ca” class=“webim-textarea” value=“”
- onKeyDown1=“javascript:butonclick();” onFocus=“clear()” cols=“” rows=“” />
- <!–请在下面文本框里输入你想要聊天的内容,禁止输入#等无意义的字符和违法信息。–>
- </div>
- <div class=“webim-body-comtent-footer”>
- <button class=“webim-body-comtent-submit” onClick=“custom_colse()”>关闭</button>
- <button class=“webim-body-comtent-submit” id=“do”
- onClick=“sendMyMessage()”>发送</button>
- <a target=“_blank” href=“#”><!–您可以直接按enter键发送内容 –>webim在线聊天>></a>
- <div id=“imjs-empty-tip” class=“webim-body-footer-tips”
- style=“display: none”><s> </s>发送内容不能为空哦</div>
- <div id=“imjs-selectuser-tip” class=“webim-body-footer-tips”
- style=“display: none”><s> </s>请您选择用户哦</div>
- </div>
- <style type=“text/css”>
- #mid_mid {
- position: relative;
- background: #f3f3f3;
- height: 14px;
- line-height: 14px;
- padding: 6px 0 6px 0px;
- width: 690px;
- }
- textarea {
- width: 400px;
- height: 66px;
- }
- .webim-body-content-textarea .webim-textarea {
- padding: 0px;
- resize: none;
- width: 690px;
- height: 50px;
- border: 0;
- font-size: 12px;
- overflow-y: auto;
- border: 1px solid #d2d2d2;
- }
- .webim-body-comtent-footer {
- position: relative;
- height: 38px;
- line-height: 28px;
- background: #f3f3f3;
- border: 1px solid #d2d2d2;
- border-left: 0;
- border-right: 0;
- width: 690px;
- }
- .webim-body-comtent-footer a {
- text-decoration: none;
- font-size: 12px;
- }
- .webim-body-comtent-submit {
- cursor: pointer;
- float: right;
- margin: 2px 0;
- margin-left: 5px;
- width: 80px;
- display: block;
- background: #fd9603;
- color: #fff;
- height: 32px;
- line-height: 31px;
- text-align: center;
- }
- </style>
- <script>
- function butonclick()
- {
- //点击enter键可以直接发送信息的功能
- if(event.keyCode == 13)
- {
- //判断输入的内容是否为空
- var textMessage = document.getElementById(‘textMessage’).value;
- if(textMessage==”)
- {
- alert(‘您还没有输入内容哦’);
- return;
- }
- //判断是不是通过enter回车键提交
- var button = document.getElementById(“do”);
- button.click();
- //清空当前textarea域的内容
- document.getElementById(“textMessage”).value==”;
- return false;
- }
- }
- var a= document.getElementById(“textMessage”);
- function clear()
- {
- if(a.value==’请在下面文本框里输入你想要聊天的内容,禁止输入#等无意义的字符和违法信息’)
- {
- a.value=”;
- }
- }
- //时间
- function mytime(){
- var now=(new Date()).getHours();
- if(now>0&&now<=6)
- {
- return “午夜好”;
- }else if(now>6&&now<=11){
- return “早上好”;
- }else if(now>11&&now<=14){
- return “中午好”;
- }else if(now>14&&now<=18){
- return “下午好”;
- }else{
- return “晚上好”;
- }
- }
- //替换所有的回车换行
- function trim2(content)
- {
- var string = content;
- try{
- string=string.replace(/\r\n/g,“<br />”)
- string=string.replace(/\n/g,“<br />”);
- }catch(e) {
- alert(e.message);
- }
- return string;
- }
- //替换所有的空格
- function trim(content)
- {
- var string = content;
- try{
- string=string.replace(/ /g,“ ”)
- }catch(e) {
- alert(e.message);
- }
- return string;
- }
- //离开当前页面时js提示关闭
- function custom_colse()
- {
- if(confirm(“您即将离开本页面,离开后无法继续与对方聊天,确定要终止本次聊天吗?”))
- {
- window.opener=null;
- window.open(”,’_self’);
- window.close();
- ws.send(“disconnection”);
- }else{}
- }
- </script>
- </body>
- </html>