我想从客户端发送命令到服务器示例更改图像URL或标签文本。我设法让服务器和服务器之间的连接工作。客户端和按钮单击工作,但我无法操作index.js文件中的DOM。有没有坚实的方法来做到这一点?我的客户端使用PHP从mySQL数据库获取数据,并且我希望将该数据作为数组传递给服务器并呈现给查看。到目前为止,这是我的代码:
server: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());
});
});
我希望它能像这样工作: 服务器: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");
});
});
谢谢:)
答案 0 :(得分:0)
让它发挥作用。不得不在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 />');
});
答案 1 :(得分:0)
socket.io, BackEnd 和 FrontEnd 有两个方面。
在上面的代码中,您试图像document.getElementById("mediaContainer").innerHTML = "Paragraph changed!";
那样操纵DOM,但这是FrontEnd部分。
socket.io 如何工作是你使用FrontEnd中socket提供的js向BackEnd中的套接字将要监听的服务器发出一些东西。然后,您从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);
});
});
这应该有效。干杯!!