I'm working with socket.io and node.js . i am able to broadcast messages from server to all clients but i am facing problem while sending the message from server to specific clients. i am new to this socket.io and node.js
below is code snipped for clients and serve
server code :
var http = require('http'),
fs = require('fs');
var express = require('express');
var app = http.createServer(function (request, response) {
fs.readFile("client.html", 'utf-8', function (error, data) {
if(error)
{
responce.writeHead(404);
responce.write("File does not exist");
responce.end();
}
else
{
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
}
});
}).listen(1337);
var io = require('socket.io').listen(app);
var clients = [ ] ;
var socketsOfClients = {};
io.sockets.on('connection', function(socket)
{
socket.on('message_to_server', function(data)
{
clients.push(socket.id);
socket(clients[0]).emit("message_to_client" , { message: data["message"] });
});
});
~
clients code :
<!DOCTYPE html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
// our socket.io code goes here
var socketio = io.connect("127.0.0.1:1337");
socketio.on("message_to_client", function(data) {
document.getElementById("chatlog").innerHTML = ("<hr/>" +
data['message'] + document.getElementById("chatlog").innerHTML);
});
function sendMessage() {
var msg = document.getElementById("message_input").value;
socketio.emit("message_to_server", { message : msg});
}
</script>
</head>
<body>
<input type="text" id="message_input"/>
<button onclick="sendMessage()">send</button>
<div id="chatlog"></div>
</body>
</html>
~
when i am executing ,it is giving error like :
socket(clients[0]).emit("message_to_client" , { message: data["message"] });
^
TypeError: object is not a function at Socket.