初识socket.io,上几行代码

 本来后端已经写好轮询的接口,但是持续的http请求及其浪费资源,所以还是了解了一下websocket。由于做支付的需要了解了一下websocket。可查看socket.io 官方demo——一个简易的聊天程序。

 需要的工具Node,使用的web框架express,自行安装。直接上代码吧~!基本把demo的代码copy了一遍。

服务端Node.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/',function(req,res){
//	res.send('<h1>Hello word </h1>');
	res.sendFile(__dirname + '/index.html')
});

http.listen(3000,function(){
	console.log('request succeed!')
})

io.on('connection',function(socket){
	socket.on('chat message',function(msg){
		socket.emit('return message', msg);
	})
});
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>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
  <script src="https://code.jquery.com/jquery-1.11.1.js"></script>

  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button type="submit">Send</button>
    </form>
	<script>
	   $(function () {
		    var socket = io();
		    $('button').click(function(){
	    	  console.log('发送');
		      socket.emit('chat message', $('#m').val());
		      $('#m').val('');
		      return false;
		    });
		    
	      	socket.on('return message',function(msg){
		      	console.log('接收');
		      	$('#messages').append($('<li>').text(msg));
		    });
	  	});
	</script>
  </body>
</html>
运行

node index
效果








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值