跟我一起使用socket.io创建聊天应用

安装express插件

新建index.js
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
  res.send('<h1>Hello world</h1>');
});
http.listen(9000, function(){
  console.log('listening on *:9000');
});
使用node index.js运行
页面中展示

目前在index.js中我们是通过res.send返回一个HTML字符串,如果我们将整个应用的HTML代码都放到应用代码里,代码结构将变得混乱。
替代方法是新建一个index.html作为服务器响应
//index.js
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
//   res.send('<h1>Hello world</h1>');
res.sendFile(__dirname + '/index.html');
});
http.listen(9000, function(){
  console.log('listening on *:9000');
});
index.html中的内容为
<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>
重新运行为

我们发送消息里面什么反应都没有
我们在这个里面集成Socket.io
Socket.io由两部分组成:
一个服务端用于集成或挂载到Node.jsHTTP服务器:socket.io
一个加载到浏览器中的客户端:socket.io-client
开发环境下,socket.io会自动提供客户端,安装socket.io

在index.js中添加模块
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
  console.log('a user connected');
});
http.listen(9000, function(){
  console.log('listening on *:9000');
});
在index.html中添加
  <script src="/socket.io/socket.io.js"></script>
    <script>
    var socket = io();
    </script>
现在index.html为
<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script>
    var socket = io();
    </script>
  </body>
</html>
运行效果为

socket.io的核心理念是允许发送,接收任意事件和任意数据,任意能被编码为JSON的对象都可以用于传输,二进制也是支持的
在客户端中,我们捕获 chat message 事件,并将消息添加到页面中。现在客户端代码应该如下:
<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
    var socket = io();
    </script>
    <script>
        $(function () {
            var socket = io();
            $('form').submit(function(){
            socket.emit('chat message', $('#m').val());
            $('#m').val('');
            return false;
            });
            socket.on('chat message', function(msg){
            $('#messages').append($('<li>').text(msg));
            });
        });
    </script>
  </body>
</html>
index的代码为
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
    socket.on('chat message', function(msg){
        io.emit('chat message', msg);
      });
});
http.listen(9000, function(){
  console.log('listening on *:9000');
});
运行项目为

本文学习自:https://www.w3cschool.cn/socket/socket-ulbj2eii.html
跟我一起使用socket.io创建聊天应用的更多相关文章
- 基于Node.js+socket.IO创建的Web聊天室
		
这段时间进了一个新的项目组,项目是用Appcan来做一个跨平台的移动运维系统,其中前台和后台之间本来是打算用WebSocket来实现的,但写好了示例后发现android不支持WebSocket,大为受 ...
 - 使用socket.io搭建聊天室
		
最近在学习nodejs,需要找一些项目练练手.找来找去发现了一个聊天室的教程,足够简单,也能从中学到一些东西.下面记录我练习过程中待一些笔记. nodeJS模块 共用到了2个模块,express和so ...
 - node.js + socket.io实现聊天室一
		
前段时间,公司打算在社区做一个聊天室.决定让我来做.本小白第一次做聊天类功能,当时还想着通过ajax请求来实现.经过经理提示,说试试当前流行的node.js 和socket.io来做.于是就上网学习研 ...
 - 使用 Socket.IO 开发聊天室
		
前言 Socket.IO 是一个用来实现实时双向通信的框架,其本质是基于 WebSocket 技术. 我们首先来聊聊 WebSocket 技术,先设想这么一个场景: · 用户小A,打开了某个网站的充值 ...
 - NodeJS + Socket.io搭建聊天服务器
		
第一步:安装node git clone https://github.com/joyent/node.git cd node git checkout v0.10.33-release ./conf ...
 - 我的学习笔记之node----node.js+socket.io实时聊天(2)
		
废话不多说,直接贴代码吧.注释很详细了. 服务端代码: /** * Created by LZX on 2015/10/7. */(function () { var d = document, w ...
 - 我的学习笔记之node----node.js+socket.io实时聊天(1) (谨此纪念博客开篇)
		
本想着从hello word开篇,也确实写了相关学习笔记.各种原因吧,现在又着急写出作品,便作罢. 这里将记录一个node.js+socket.io的实时聊天程序.(当然我也是跟着网上各种教程资料学习 ...
 - Socket.io在线聊天室
		
从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发.Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎.chrome浏 ...
 - nodejs+socket.io即时聊天实例
		
在这之前你应该先安装好 Node.js,安装过程不再讲解 首先在你的电脑上创建一个新目录,姑且命名为 chat,然后在该目录创建两个文件,分别是 app.js 和 index.html. app.js ...
 
随机推荐
- Linux ifconfig  单网卡配置多网段
			
1 2 3 4 5 6 7 8 9 10 11 ifconfig eth0 down ifconfig eth0 hw ether 01:02:03:04:05:06 ifconfig eth0 ...
 - Python的变长参数
			
Python的变长参数 def foo1(*args): for arg in args: print arg def foo2(**kargs): for key in kargs: print k ...
 - LeetCode 181. Employees Earning More Than Their Managers (超过经理收入的员工)
			
题目标签: 题目给了我们一个 员工表,包括经理.员工会有经理的id. 这里可以重复 利用两次 表格,表格a, 表格b,当a 员工的经理id 等于 b员工时候,在从中找到员工工资大于经理的.具体看co ...
 - scrapy的使用--Rcrapy-Redis
			
Scrapy-Redis分布式爬虫组件 Scrapy是一个框架,他本身是不支持分布式的.如果我们想要做分布式的爬虫.就需要借助一个组件叫做Scrapy-Redis.这个组件正式利用了Redis可以分布 ...
 - 2019-2020 ACM-ICPC Latin American Regional Programming Contest
			
代码见:戳 easy: EIM medium-easy: BDFKL medium: ACJ medium-hard: H A - Algorithm Teaching 题意 给一些集合,现从每个集合 ...
 - Palindrome Partition CodeForces - 932G 回文树+DP+(回文后缀的等差性质)
			
题意: 给出一个长度为偶数的字符串S,要求把S分成k部分,其中k为任意偶数,设为a[1..k],且满足对于任意的i,有a[i]=a[k-i+1].问划分的方案数. n<=1000000 题解: ...
 - 【笔记篇】(理论向)快速傅里叶变换(FFT)学习笔记w
			
现在真是一碰电脑就很颓废啊... 于是早晨把电脑锁上然后在旁边啃了一节课多的算导, 把FFT的基本原理整明白了.. 但是我并不觉得自己能讲明白... Fast Fourier Transformati ...
 - Leetcode274.H-IndexH指数
			
原题的中文翻译不是很好,所以给出英文版. Given an array of citations (each citation is a non-negative integer) of a rese ...
 - Connected Graph
			
Connected Graph 求n个点的无向联通图数量,\(n\leq 50\). 解 直接无向联通图做状态等于是以边点做考虑,难以去重,考虑联通对立面即不联通. 不难求出n个点的总方案数为\(2^ ...
 - PKUSC加油加油加油!
			
一句话,把学过的掌握的甚至还未掌握的,都用上吧! 1.题目不要再再再看错了!在纸上记下关键字. 2.记得有预处理这个东西可以降低复杂度! 3.仔细阅读数据范围,取值范围的0要注意! 4.不要每次像开新 ...