html5-websocket聊天例子

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset=utf-8 /> 
<meta name="viewport" content="width=620" /> 
<title>HTML5 Demo: Web Socket</title> 
<link rel="stylesheet" href="http://html5demos.com/css/html5demos.css" type="text/css" /> 
<script src="http://html5demos.com/js/h5utils.js"></script></head> 
<body> 
<section id="wrapper"> 
    <header> 
      <h1>Web Socket</h1> 
    </header> 
<style> 
#chat { width: 97%; }
.them { font-weight: bold; }
.them:before { content: 'them '; color: #bbb; font-size: 14px; }
.you { font-style: italic; }
.you:before { content: 'you '; color: #bbb; font-size: 14px; font-weight: bold; }
#log {
  overflow: auto;
  max-height: 300px;
  list-style: none;
  padding: 0;
/*  margin: 0;*/
}
#log li {
  border-top: 1px solid #ccc;
  margin: 0;
  padding: 10px 0;
}
</style> 
<article> 
  <form> 
    <input type="text" id="chat" placeholder="type and press enter to chat" /> 
  </form> 
  <p id="status">Not connected</p> 
  <p>Users connected: <span id="connected">0</span></p> 
  <p>To test, open two windows with Web Socket support, type a message above and press return.</p> 
  <p>The server side code is available here: <a href="http://github.com/remy/html5demos/tree/master/server/">node-web-socket & server</a> (note that it runs on <a href="http://nodejs.org/" title="node.js">nodejs</a>)</p> 
  <ul id="log"></ul> 
</article> 
<script> 
function openConnection() {
  // uses global 'conn' object
  if (conn.readyState === undefined || conn.readyState > 1) {
    conn = new WebSocket('ws://node.remysharp.com:8001');    
    conn.onopen = function () {
      state.className = 'success';
      state.innerHTML = 'Socket open';
    };
 
    conn.onmessage = function (event) {
      var message = JSON.parse(event.data);
      if (typeof message == 'string') {
        log.innerHTML = '<li class="them">' + message.replace(/[<>&]/g, function (m) { return entities[m]; }) + '</li>' + log.innerHTML;
      } else {
        connected.innerHTML = message;
      }
    };
    
    conn.onclose = function (event) {
      state.className = 'fail';
      state.innerHTML = 'Socket closed';
    };
  }
}
 
var connected = document.getElementById('connected'),
    log = document.getElementById('log'),
    chat = document.getElementById('chat'),
    form = chat.form,
    conn = {},
    state = document.getElementById('status'),
    entities = {
      '<' : '<',
      '>' : '>',
      '&' : '&'
    };
 
 
if (window.WebSocket === undefined) {
  state.innerHTML = 'Sockets not supported';
  state.className = 'fail';
} else {
  state.onclick = function () {
    if (conn.readyState !== 1) {
      conn.close();
      setTimeout(function () {
        openConnection();
      }, 250);
    }
  };
  
  addEvent(form, 'submit', function (event) {
    event.preventDefault();
 
    // if we're connected
    if (conn.readyState === 1) {
      conn.send(JSON.stringify(chat.value));
      log.innerHTML = '<li class="you">' + chat.value.replace(/[<>&]/g, function (m) { return entities[m]; }) + '</li>' + log.innerHTML;
      
      chat.value = '';
    }
  });
 
  openConnection();  
}
 
</script><a id="html5badge" href="http://www.w3.org/html/logo/"> 
<img src="http://www.w3.org/html/logo/badge/html5-badge-h-connectivity-device-graphics-multimedia-performance-semantics-storage.png" width="325" height="64" alt="HTML5 Powered with Connectivity / Realtime, Device Access, Graphics, 3D & Effects, Multimedia, Performance & Integration, Semantics, and Offline & Storage" title="HTML5 Powered with Connectivity / Realtime, Device Access, Graphics, 3D & Effects, Multimedia, Performance & Integration, Semantics, and Offline & Storage"> 
</a> 
    <footer><a href="/">HTML5 demos</a>/<a id="built" href="http://twitter.com/rem">@rem built this</a>/<a href="#view-source">view source</a></footer> 
</section> 
<a href="http://github.com/remy/html5demos"><img style="position: absolute; top: 0; left: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_left_darkblue_121621.png" alt="Fork me on GitHub" /></a> 
<script src="http://html5demos.com/js/prettify.packed.js"></script> 
<script> 
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script> 
<script> 
try {
var pageTracker = _gat._getTracker("UA-1656750-18");
pageTracker._trackPageview();
} catch(err) {}</script> 
</body> 
</html> 



小张网校

www.xiaozhangwx.com
-IT编程在线学习交流平台
-更多的小伙伴等待你的加入


最新视频课程:
2048游戏的开发


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是关于WebSocket实例的简单多人聊天室的教程: 在这个例子中,我们将创建一个简单的多人聊天室,用户可以在其中发送消息,同时所有连接到聊天室的用户都将看到这些消息。 1. 首先,我们需要一个HTML页面,用于显示聊天室的界面。创建一个新文件`index.html`,并添加以下内容: ```html <!DOCTYPE html> <html> <head> <title>WebSocket Chat Room</title> </head> <body> <div id="chatBox"></div> <form> <input type="text" id="messageInput" /> <button type="submit">Send</button> </form> <script src="chat.js"></script> </body> </html> ``` 这是一个非常简单的HTML页面,其中包含一个`<div>`元素,用于显示聊天记录,以及一个`<form>`元素,用于发送新的聊天消息。我们还添加了一个JavaScript文件`chat.js`,稍后我们将在其中编写聊天室的逻辑。 2. 接下来,我们需要编写聊天室的服务器端代码。创建一个新文件`server.js`,并添加以下内容: ```javascript const WebSocket = require("ws"); const server = new WebSocket.Server({ port: 8080 }); const connections = []; server.on("connection", (socket) => { console.log("New client connected"); connections.push(socket); socket.on("message", (message) => { console.log(`Received message: ${message}`); connections.forEach((connection) => { if (connection !== socket) { connection.send(message); } }); }); socket.on("close", () => { console.log("Client disconnected"); const index = connections.indexOf(socket); if (index > -1) { connections.splice(index, 1); } }); }); ``` 这是一个非常简单的WebSocket服务器,它监听端口`8080`上的所有连接。每当有新客户端连接时,服务器都会将其添加到`connections`数组中。当服务器收到任何消息时,它将将该消息发送给所有其他连接的客户端。当客户端断开连接时,服务器将从`connections`数组中删除该客户端。 3. 最后,我们需要编写客户端代码,用于连接到聊天室并发送消息。在`chat.js`文件中添加以下内容: ```javascript const socket = new WebSocket("ws://localhost:8080"); const chatBox = document.getElementById("chatBox"); const messageInput = document.getElementById("messageInput"); socket.onmessage = (event) => { const message = event.data; const messageElement = document.createElement("div"); messageElement.innerText = message; chatBox.appendChild(messageElement); }; document.querySelector("form").addEventListener("submit", (event) => { event.preventDefault(); const message = messageInput.value.trim(); if (message.length > 0) { socket.send(message); messageInput.value = ""; } }); ``` 这是一个非常简单的WebSocket客户端,它连接到服务器端口`8080`,并通过`onmessage`事件处理程序处理来自服务器的任何消息。每当客户端发送新消息时,它将通过`socket.send`方法将该消息发送到服务器。 4. 最后,启动服务器:在终端中运行`node server.js`。 5. 在浏览器中打开`index.html`文件,你应该看到一个简单的聊天室界面。在多个浏览器窗口中打开该界面,并尝试在其中一个窗口中发送消息。你将看到该消息立即显示在所有窗口中。 现在你已经创建了一个简单的WebSocket聊天室,你可以扩展它以包括更多功能,例如昵称、私人消息、表情符号等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值