我试图像这样向客户端发送字符串:
socket.emit("start", "calm");
但是它抛出一个错误,是因为它不是对象吗?
答案 0 :(得分:3)
首先,您应该确保服务器端和客户端之间的套接字已连接。并向套接字注册事件和功能。
服务器端
io.sockets.on('connection', function(socket) {
console.log('socket connect' + socket.id);
// when a client connect to server within socket, server will send hello
io.emit('newMsg', "hello")
socket.on('disconnect', function() {
console.log('socket disconnect');
})
// when server receive a message, it will send to all client which connect
to the server
socket.on('data', function (data) {
console.log(socket.id +': ' + data.msg);
var message = {from: socket.id,
msg: data.msg
}
io.emit('newMsg', message)
})
}
客户端
var socket = io('http://localhost:3000');
socket.on('connect', function (data) {
console.log(data)
})
socket.on('newMsg', function(data) {
console.log(data)
})
// function could bind on button on client side page, get input and send data
function sendData() {
var input = document.getElementsByTagName('input')
var text = input[0].value
var data = { msg: text }
socket.emit('data', data)
}
打开控制台,该信息将显示在控制台中。在服务器端发送消息时,也可以使用“广播”代替“发送”,以将消息发送给除您之外的其他客户端。阅读文档:socket.io doc