[英]Socket.io Emit doesn't work
I'm a newbie in NodeJS and I just started creating a simple chat app with Express and Socket.io but It the "message" emit part is not working (socket.on('connect') works!). 我是NodeJS的新手,我刚刚开始使用Express和Socket.io创建一个简单的聊天应用程序,但是“消息”发出部分不起作用(socket.on('connect')起作用!)。 The alert "OK" works fine but console.log doest nothing.
警报“确定”工作正常,但console.log没有执行任何操作。
Here is my code: 这是我的代码:
App.js App.js
var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); app.get('/', function(req, res,next) { res.sendFile(__dirname + '/index.html'); }); app.get('/test', function(req, res,next) { res.render('HALLO '); }); server.listen(4200); io.on('connection', function(client) { // var address = io.handshake.address; console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ') }); io.on('sendmsg', function(data) { console.log(data); });
Index.html 的index.html
<script src="/socket.io/socket.io.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script> var socket = io.connect('http://localhost:4200'); function sendMsg(){ alert("OK"); socket.emit('sendmsg', document.getElementById("text").value); } </script> <h2>Awesome Chat by Simon</h2> <br> <input type="text" id="text"> <input type="button" onclick="sendMsg()" value="Senden">
You listen on individual socket
. 您在单个
socket
上收听。 Move your listener from io
to client
将您的监听器从
io
移至client
io.on('connection', function(client) {
// var address = io.handshake.address;
console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ')
client.on('sendmsg', function(data) {
console.log(data);
});
});
You should move your handler inside the on connection
function like this: 您应该像这样在on
connection
函数中移动处理程序:
io.on('connection', function(client) {
// var address = io.handshake.address;
console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ');
client.on('sendmsg', function(data) { // Move this part inside the connection function
console.log(data);
});
});
The event gets triggered on the socket ( client
) not on the server: 该事件在套接字(
client
)而非服务器上触发:
io.on('connection', function(client) {
// var address = io.handshake.address;
console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ');
client.on("sendmsg", console.log);
});
Try doing this way. 尝试这样做。
io.on('connection', function(client) {
console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ')
client.on('sendmsg', function(data) {
console.log(data);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.