服务器代码
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on("connection",()=>{
console.log("Connected");
});
server.listen(3000,()=>{
console.log("Ready");
});
客户代码
const io = require('socket.io-client');
const socket = io('http://127.0.0.1:3000');
socket.connect();
执行代码,没有错误。 只是无法连接。
为什么?!
答案 0 :(得分:0)
//let's have a simple example
//Server
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
server.listen(8080);
//Client
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/');
</script>
//Sending Data from Server to Client
//Server
io.on('connection', function(socket) {
socket.emit('announcements', { message: 'A new user has joined!' });
});
//Client
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/');
socket.on('announcements', function(data) {
console.log('Got announcement:', data.message);
});
</script>
//Sending Data from Client to Server
//Server
io.on('connection', function(socket) {
socket.on('event', function(data) {
console.log('A client sent us this dumb message:', data.message);
});
});
//Client
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/');
socket.emit('event', { message: 'Hey, I have an important message!' });
</script>