http://socket.io/#how-to-use的客户端是这么写的
CLIENT (INDEX.HTML)
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
How do I serve the client (https://github.com/LearnBoost/Socket.IO/wiki/How-do-I-serve-the-client)
The client is served automatically by the Node.JS server. In your
tag of your HTML, include:
If your web app and socket.io are on the same server and port, you can simply include:
Socket.io client can also include optional version numbers, in order to maximize caching performance. You can simply include the version number within javascript filename;
If you choose to serve the client through other means, you can clone the socket.io-client
repository and look at the dist/
subdirectory.
我自己用的是8888端口
"/socket.io/socket.io.js" socket.io.js此文件在此目录不存在
正确目录为 node_modules\socket.io\lib 但改为正确目录,再运行文件进行连接时,显示上段代码中的 IO undefined
试了网上说的在地址前面的 localhost 但同样不行
换回"/socket.io/socket.io.js" 既能正确访问
不知道为何。。。记录待解决
/************2
在浏览器访问http://localhost:8888/socket.io/socket.io.js 可以得到socket.io.js文件内容
一直认为localhost:8888应该是 server.js 的目录 ,因为index.html 同在这个目录。
但这样看好像不是。
另建一个 1/index.html访问 仍对。因此localhost:8888应该是 server.js 的目录。
但在此目录找不到 socket文件夹
看server.js文件
有句
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
.rese.writeHead方法表示,服务器端回应一个HTTP头信息;
response.end方法表示,服务器端回应的具体内容,以及回应完成后关闭本次对话。
readFileSync是读取文件的操作
_dirname:指向当前运行的脚本所在的目录。
//插句--到这突然发现自己对服务器的理解有误,页面是服务器端回应才显示的,而不是主动访问的。是主动访问服务器,然后服务器回应页面
想看目录地址,因此在server.js加了一句 console.log(__dirname); 想在服务器端输出 地址
输出:
info - socket.io started
Listening at: http://localhost:8888
F:\nodejs
地址没错。
那么F:\nodejs\socket.io\socket.io.js 在哪?
/*************
突然发现
info - socket.io started
这一句,会不会是在服务器端建立的时候同时新建了整个文件?
访问客户端页面,服务端出现以下消息:
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized nBdiU__gmVQRumBZfSAB
debug - setting request GET /socket.io/1/websocket/nBdiU__gmVQRumBZfSAB
debug - set heartbeat interval for client nBdiU__gmVQRumBZfSAB
debug - client authorized for
debug - websocket writing 1::
单词基本认识,但不太懂什么意思。。。
(authorized)
['ɔːθəraɪzd] adj. 经授权的;经认可的
(interval) ['ɪntəv(ə)l] n. 间隔;间距;幕间休息
回头看server.js文件,之前都在试例子,没看每句的具体含义:(看完回来再写)(随手问题:就算是服务启动才新建了一个,但如果客户端引入网络上的socket.io文件应该是可以访问,执行的,但为何同样不行,17.30吃饭去)