Javascript 使用socket.io创建hello world应用程序
当我在客户机上运行时,会打印Hello World,但我编写的控制台日志并没有显示客户机和服务器上的事件。为什么? 客户端代码:Javascript 使用socket.io创建hello world应用程序,javascript,node.js,socket.io,cygwin,Javascript,Node.js,Socket.io,Cygwin,当我在客户机上运行时,会打印Hello World,但我编写的控制台日志并没有显示客户机和服务器上的事件。为什么? 客户端代码: <script src="C:\cygwin\usr\local\lib\node\.npm\socket.io\0.6.10\package\support\socket.io-client\socket.io.js"></script> <script> var socket = new io.Socket('http:/
<script src="C:\cygwin\usr\local\lib\node\.npm\socket.io\0.6.10\package\support\socket.io-client\socket.io.js"></script>
<script>
var socket = new io.Socket('http://localhost:8080/');
socket.connect();
socket.on('connect', function(){
console.log("on connect");
}) ;
socket.on('message', function(){
console.log("on message");
}) ;
socket.on('disconnect', function(){
console.log("on disconn");
}) ;
</script>
var socket=新io.socket('http://localhost:8080/');
socket.connect();
socket.on('connect',function(){
console.log(“on connect”);
}) ;
socket.on('message',function(){
console.log(“登录消息”);
}) ;
socket.on('disconnect',function(){
console.log(“在discon上”);
}) ;
服务器代码:
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
server = http.createServer(function(req, res){
// your normal server code
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello world</h1>');
});
server.listen(8080);
// socket.io
var socket = io.listen(server);
socket.on('connection', function(client){
// new client is here!
client.on('message', function(){
console.log("on message");
})
client.on('disconnect', function(){
console.log("on disconnect");
})
});
var http=require('http'),
io=require('socket.io'),//对于npm,否则使用require('./path/to/socket.io'))
server=http.createServer(函数(req,res){
//您的正常服务器代码
res.writeHead(200,{'Content-Type':'text/html'});
res.end(“你好,世界”);
});
监听服务器(8080);
//socket.io
var socket=io.listen(服务器);
socket.on('connection',函数(客户端){
//新客户来了!
on('message',function(){
console.log(“登录消息”);
})
client.on('disconnect',function()){
控制台日志(“断开连接”);
})
});
试试看
而不是
var socket = new io.Socket('http://localhost:8080/');
这可能是因为浏览器同源安全限制-socket.io客户端库不是来自您连接的服务器
我不知道非常古老的0.6.9,但较新版本的
socket.io
会自动为socket.io客户端提供服务,因此您应该使用/socket/socket.io.js
而不是当前使用的文件://
URL。查看文档中的确切URL。在这种情况下,您希望看到哪些日志消息?简单连接将仅在客户端上输出“on connect”。如果您正在运行Firefox,请确保Firebug正在运行,否则您将看不到日志。
var socket = new io.Socket('http://localhost:8080/');