一段最简单的使用socket.io进行服务器和客户端通信的例子代码
生活随笔
收集整理的這篇文章主要介紹了
一段最简单的使用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的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的一段最简单的使用socket.io进行服务器和客户端通信的例子代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在SAP云平台上创建Redis实例
- 下一篇: CWMP开源代码研究3——ACS介绍