在我的Web-App中我想使用websocket连接我的应用程序和服务器中的html文件。 (使用socket.io)
我可以在本地打开文件时立即启动套接字连接(例如file:///../../file.htm)而不是服务器端http://localhost/吗?
在如下的简单示例中,这怎么可能?
客户端:
var socket = io();
socket.on('connect', function () {
socket.emit('a', 'b', function (data) {
console.log(data);
});
});
服务器:
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
io.sockets.on('connection', function (socket) {
console.log('socket connected');
socket.on('disconnect', function () {
console.log('socket disconnected');
});
});
http.listen(80, (ff) =>
console.log('Example app listening on port 80!'));
答案 0 :(得分:0)
这是最基本的socket.io服务器:
const io = require('socket.io')(3000);
io.on('connection', function (socket) {
console.log('client connected');
socket.on('disconnect', () => {
console.log('client disconnected');
});
});
console.log('socket.io server started at port 3000');
以及您可以在浏览器中以文件:///client.html打开的html客户端:
<!doctype html>
<html>
<body>
<h1>Testing socket.io</h1>
<h3 id="socket">waiting...</h3>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"></script>
<script>
var socket = io('http://localhost:3000');
socket.on('connect', function() {
document.getElementById("socket").innerHTML = "socket connected";
});
socket.on('disconnect', function() {
document.getElementById("socket").innerHTML = "socket disconnected";
});
</script>
</body>
</html>