核心提示:如果你想创建一个应用,浏览器与服务器需要正式的对话,那你可能使用XMLHttpRequest对象,使用xmlHttpRequest对象在很多时候是没有问题的,但同样也有很多情况不合适。首先,XMLHt...
如果你想创建一个应用,浏览器与服务器需要正式的对话,那你可能使用XMLHttpRequest对象,使用xmlHttpRequest对象在很多时候是没有问题的,但同样也有很多情况不合适。首先,XMLHttpRequest不适合快速的来回发送多条消息。其次没有办法将一次调用与下一次调用联系起来,每次网页发送请求,服务器都要确定请求来自何方。在这种情况下,要想把一系列请求关联起来,服务器代码会变得非常的复杂。所以现在出现了WebSocket,根据websocket,浏览器能够保持对web服务器打开的连接,从而服务器长时间交换数据。
webSocket主要用来编写聊天程序,多人游戏或者端对端的协作工具,但是websocket的服务器端的代码相对比较复杂,这里不做介绍,后面总结php这一块的时候再详细介绍。
下面直接上代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <input type="text" id="txt"> <button id="send">连接</button> <button id="close">关闭连接</button> <script type="text/javascript"> window.onload=function(){ var websocket; var oTxt = document.getElementById("txt"); var oClose = document.getElementById("close"); var oSend = document.getElementById("send"); // 建立连接,这里的ws是一种连接协议 websocket = new WebSocket("ws://localhost:90/html5/websocketserver.php"); // websocket有四个事件 // onOpen建立连接后触发 // onError出现问题时触发 // onClose连接关闭时触发 // onMessage从服务器收到消息时触发 oClose.onclick=function(){ websocket.onclose = connectionClose; } oSend.onclick=function(){ websocket.onopen = connectionOpen; } websocket.onmessage = messageReceived; websocket.onerror = errorOccurred; // 连接成功发送一条消息 function connectionOpen(){ websocket.send("username:"+oTxt.value); } function messageReceived(e){ console.log("你接收到的数据为"+e.data); } function errorOccurred(){ alert("服务器连接出错"); } function connectionClose(){ alert("连接已经关闭"); } } </script> </body> </html>