我是Node js的新手,刚刚通过socket.io和express js接触,我想知道它们之间的区别或它们之间的关系。我有一些用于聊天应用程序的小代码
在 nodeClient.js
var socket = io.connect( 'http://localhost:8080' );
$( "#messageForm" ).submit( function() {
var nameVal = $( "#nameInput" ).val();
var msg = $( "#messageInput" ).val();
alert("msg");
socket.emit( 'message', { name: nameVal, message: msg } );
// Ajax call for saving datas
$.ajax({
url: "./ajax/insertNewMessage.php",
type: "POST",
data: { name: nameVal, message: msg },
success: function(data) {
}
});
return false;
});
socket.on( 'message', function( data ) {
var actualContent = $( "#messages" ).html();
alert(actualContent);
var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' + data.message + '</li>';
var content = newMsgContent + actualContent;
$( "#messages" ).html( content );
});
并在 nodeServer.js
var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );
var app = express();
var server = http.createServer( app );
var io = socket.listen( server );
io.sockets.on( 'connection', function( client ) {
console.log( "New client !" );
client.on( 'message', function( data ) {
console.log( 'Message received ' + data.name + ":" + data.message );
//client.broadcast.emit( 'message', { name: data.name, message: data.message } );
io.sockets.emit( 'message', { name: data.name, message: data.message } );
});
});
server.listen( 8080 );
现在,来到我的怀疑点
在 nodeServer.js 文件中,我有
var socket = require( 'socket.io' );
var express = require( 'express' );
var app = express();
var server = http.createServer( app );
var io = socket.listen( server );
我可以观察到socket和express之间有一些关系,谁能解释一下这两者的关系和用法。
这将帮助我进一步进入更多节点 js 应用程序
谢谢!