一段最簡單的使用socket.io進行伺服器和客戶端通訊的例子程式碼

汪子熙發表於2019-03-08

伺服器端程式碼:

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');
});

伺服器端輸出:
clipboard1

客戶端輸出:
clipboard2

要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":

相關文章