就像我想要创建一个服务器,它从一个客户端接收消息并将其发送到另一个客户端。(两个客户端之间通过服务器的双向通信)nodejs中的哪个库适合这个?关于这个的任何教程?
提前致谢:)
答案 0 :(得分:0)
试试这个示例代码,您将了解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
键入一条消息,然后单击“发送”按钮。希望这会有所帮助。