欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

node.js 用socket實(shí)現(xiàn)聊天的示例代碼

 更新時(shí)間:2017年10月17日 10:45:23   作者:哈希  
本篇文章主要介紹了node.js 用socket實(shí)現(xiàn)聊天的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

本文介紹了node.js 用socket實(shí)現(xiàn)聊天的示例代碼,分享給大家,也給自己留個(gè)筆記,具體如下:

服務(wù)器搭建

app.js

const http = require("http");
const express = require("./express");

//創(chuàng)建一個(gè)服務(wù)
const server = http.createServer(express);

//監(jiān)聽(tīng)服務(wù)端口
server.listen(8001,()=>{
  console.log("服務(wù)端已經(jīng)啟動(dòng),請(qǐng)?jiān)L問(wèn) http://localhost:8001");
}); 

express.js

const url=require("url");
const fs=require("fs");

function express(req,res){
  var urlObj=url.parse(req.url);
  //console.log(urlObj);

  var filePath="./www"+urlObj.pathname;
  var content="not found";
  if(fs.existsSync(filePath)){
    content=fs.readFileSync(filePath);
  }
  
  res.end(content.toString());
}


module.exports=express; 

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
   <meta charset="utf-8"/>
    <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="js/lib/jquery-1.11.1.js"></script>
    <script src="js/lib/socket.io.js"></script> 
    <script src="js/index.js"></script>
   </body>
</html> 

客戶(hù)端服務(wù)搭建與服務(wù)端通信

我們要建立服務(wù)端socket請(qǐng)求連接

io.on('connection', function(socket){
  console.log('a user connected');

  //斷開(kāi)連接
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
}); 

index.js

//客戶(hù)端建立連接 
var socket = io(); 
客戶(hù)端向服務(wù)端發(fā)送請(qǐng)求
index.js

$('form').submit(function(){
  //觸發(fā)事件
  socket.emit('chat message', $('#m').val());
  $('#m').val('');
  return false;
 });  

app.js

//接收客戶(hù)端的信息
socket.on('chat message', function(msg){
  console.log('message: ' + msg);
}); 

將服務(wù)端的數(shù)據(jù)廣播到客戶(hù)端去

socket.on('chat message', function(msg){
    console.log('message: ' + msg);

    socket.broadcast.emit("clientE",msg);
  }); 

客戶(hù)端接收服務(wù)端廣播出來(lái)的數(shù)據(jù)

socket.on('clientE', function(msg){
  $('#messages').append($('<li>').text(msg));
}); 

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論