簡體   English   中英

如何使用Socket.io從客戶端向服務器發送命令

[英]How to send commands from client to server with Socket.io

我想將命令從客戶端發送到服務器示例,以更改圖像url或標簽文本。 我設法使服務器與客戶端之間的連接正常工作,並且單擊按鈕即可正常工作,但是我無法通過index.js文件操作DOM。 有可靠的方法嗎? 我的客戶端使用PHP從mySQL數據庫中獲取數據,我想將該數據作為數組傳遞給服務器並呈現給視圖。 到目前為止,這是我的代碼:

服務器:index.js-

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


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

//This is auto initiated event when Client connects to Your Machien.  
io.on('connection', function(client) {
    console.log('Client connected...');

    client.on('test',function(msg){
        console.log("i can see this in cmd console");

    // i would like to do like this but it says "document is not defined"

    //document.getElementById("mediaContainer").innerHTML = "Paragraph changed!";

    });

});

http.listen(3000,function(){
    console.log("Listening on 3000");
});

客戶端:app.js-

$(document).ready(function () {
    $("#button1").click(function(){
        socket.emit('test',$("#someinput").val());
    });
});

我希望它像這樣工作:server:app.js-

$(document).ready(function () {

    var socket = io.connect('http://192.168.2.65:3000');

    socket.on('test',function(msg){
        $("#mediaContainer").append(msg);
        console.log("i cant get this to work");
    });

});

謝謝 :)

得到它的工作。 必須在socket.on內制作一個socket.emit,使其與另一個服務器javascript文件捕獲,如下所示:

index.js:

client.on('test',function(value){
    io.sockets.emit('testi1',value);
});

app.js:

socket.on('testi1',function(msg){
    $("#mediaContainer").append(msg + '<br /><br />');
});

socket.io有兩個方面, BackEndFrontEnd

在上面的代碼中,您嘗試對DOM進行操作,例如document.getElementById("mediaContainer").innerHTML = "Paragraph changed!"; 但這是FrontEnd部分。

如果您使用前端中套接字提供的js向后端發出套接字監聽的服務器發送郵件, socket.io的工作原理。 然后,響應於收到的發射,您從BackEnd發射一些東西。 您還可以在FrontEnd部分向此BackEnd發射添加一個偵聽器,最后根據接收到的發射來操作DOM。

前端

 $(document).ready(function () { var socket = io.connect('http://192.168.2.65:3000'); $("#button1").click(function(){ socket.emit('test',$("#someinput").val()); }); socket.on('test',function(msg){ $("#mediaContainer").append(msg); }); }); 

后端

 io.on('connection', function(client) { console.log('Client connected...'); client.on('test',function(msg){ // If you want all including the sender to get emission client.emit('test', msg); // If you want all excluding the sender to get emission client.broadcast.emit('test', msg); }); }); 

這應該工作。 干杯!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM