一段最简单的使用socket.io进行服务器和客户端通信的例子代码

服务器端代码:

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(8880);

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  console.log("connect comming from client: " + socket.id);
  socket.emit('messages_jerry', { hello: 'world greeting from Server!' });
  socket.on('messages', function (data) {
    console.log("data received from Client:" + JSON.stringify(data,2,2));
  });
});

客户端代码:

// #!/usr/bin/env node
const io = require('socket.io-client');
var socket = io.connect('http://localhost:8880');

socket.on('messages_jerry', function (data) {
    console.log("data sent from Server:" + JSON.stringify(data,2,2));
    socket.emit('messages', { my: 'data sent from Client' });
  });

socket.on('connect', function (socket2) {
    console.log('Connection with Server established!');
        socket.emit('messages', 'Client has established connection with Server');
});

服务器端输出:

客户端输出:

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

你可能感兴趣的:(JavaScript)