【问题标题】:client to client communication through server nodejs通过服务器nodejs进行客户端到客户端的通信
【发布时间】:2017-09-07 10:09:10
【问题描述】:

就像我想创建一个服务器,它从一个客户端接收消息并将其发送到另一个客户端。(两个客户端之间通过服务器进行双向通信)nodejs 中的哪个库适合这个?有这方面的教程吗?

提前致谢:)

【问题讨论】:

  • 你在找Socket.io??
  • 是的。 socket.io 之类的..
  • 然后继续执行。谷歌一下,有很多教程可用..

标签: node.js server chat


【解决方案1】:

试试这个示例代码,您将了解 socket.io 和双向通信。

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

// Initialize appication with route / (that means root of the application)
app.get('/', function(req, res){
  var express=require('express');
  app.use(express.static(path.join(__dirname)));
  res.sendFile(path.join(__dirname,'index.html'));
});

// Register events on socket connection
io.on('connection', function(socket){ 
  socket.on('chatMessage', function(from, msg){
    io.emit('chatMessage', from, msg);
  });
  socket.on('notifyUser', function(user){
    io.emit('notifyUser', user);
  });
});

// Listen application request on port 3000
http.listen(3000, function(){
  console.log('listening on *:3000');
});

这是我命名为index.html的html文件。

<!doctype html>
  <html>
   <head>
    <title>Chat Application</title>
    <link rel='stylesheet' href='style.css' type='text/css'/>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script src="chat.js"></script>
  </head>
  <body> 
    <ul id="messages"></ul>
    <span id="notifyUser"></span>
    <form id="form" action="" onsubmit="return submitfunction();" > 
      <input type="hidden" id="user" value="" /><input id="m" autocomplete="off" onkeyup="notifyTyping();" placeholder="Type yor message here.." /><input type="submit" id="button" value="Send"/> 
    </form>
  </body>
</html>

node app.js 运行服务器并在浏览器中打开两个选项卡,在页面底部使用此api http://localhost:3000 键入一条消息并单击发送按钮..希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    相关资源
    最近更新 更多