手機端與網頁通過websocket通訊

來源:互聯網
上載者:User

標籤:nodejs   websocket   

手機端與網頁通訊,使用websocket完成二者之間的聯通。


websocket選用socket.io類實現。


伺服器端,使用nodejs,代碼依賴了express和socket.io。

首先建立一個http伺服器


var app = require(‘express‘)();

var server = require(‘http‘).Server(app);

var socketio = require(‘./v1/socketio‘);

var db = require("./db/db.js");


server.listen(80);


app.get(‘/‘, function (req, res) {

res.sendFile(__dirname + ‘/index.html‘);

});


然後用這個伺服器建立websoket服務


var io = socketio(http);


var socketarr = [];


io.on(‘connection‘, function (socket) {

console.log(‘a user connected‘);


});


聯通成功後,通過socket.io 提供的 on 和emit方法,就可以組織用戶端的通訊了。


移動端整合socket.io即可,ios和android的demo如下:

ios:https://github.com/socketio/socket.io-client-swift

android: https://github.com/socketio/socket.io-client-java


網頁裡想要整合socket.io,從socket.io首頁下載js檔案。

socket.io首頁: https://socket.io/


在網頁中嵌入

<script type="text/javascript" src="/src/socket.io.min.js" charset="UTF-8"></script>


使用以下代碼就可以串連websocket伺服器

var socket = io(‘ws://socket.liboapp.cn‘);

通過socket的on和emit方法與移動端通訊。

手機端與網頁通過websocket通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.