socket.io node.js mysql

      本案例功能是,在网页端输入数据,出入到服务器,最后存入数据库。

      第一步:网页数据传入到服务器,过程如下链接:网页聊天案例,这个案例讲解很清楚,可以自己看懂。

      服务器代码:

var app=require('express')();
var http=require('http').Server(app);
var io=require('socket.io')(http);
var mysql=require('mysql');

var connection = mysql.createConnection({
 host   : 'localhost',
 user   : 'root',
 password : '',
 database : 'summer'
});


  connection.connect();

app.get('/',function(req,res) {

  res.sendFile(__dirname + '/index.html');
});

io.on('connection',function(socket) {
  socket.on('chat message',function(msg) {

  var value=[''+msg,'2345',1];
    connection.query('insert into adinfo set Adname=?,Adpwd=?,Adlevel=?',value,function(err,rows,fields) {
       if(err) throw err;

    });



  });



});

http.listen(3000,function(){
  console.log('listen: 3000');
});

网页代码:

<!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="http://code.jquery.com/jquery-1.11.1.js"></script>
  <script>
    var socket = io();
    $('form').submit(function(){
   socket.emit('chat message', $('#m').val());
   $('#m').val('');
   return false;
 });
  </script>

</body>

</html>

数据库更新图:


留有问题:数据库链接了,但是没有断开代码,断开代码是connection.end(),但我不知道放哪,还在继续研究中。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值