I have this little socket room app, but for a reason is not working. I'm trying to make the user join the room on click and display an alert, can't figure out the issue, I'm kinda new to sockets and can't even get this simple app working.. This is my code
////app.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
});
});
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party people?');
http.listen(3000, function(){
console.log('listening on localhost:3000');
});
////index.html
<!DOCTYPE html>
<html>
<head>
<title>flip</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<button>Join the room!</button>
</body>
<script>
var socket = io.connect();
// let's assume that the client page, once rendered, knows what room it wants to join
var room = "abc123";
socket.on('connect', function() {
$('button').click(function() {
socket.emit('room', room);
})
});
socket.on('message', function(data) {
alert(data)
});
</script>
</html>
On the client side you have to:
var socket = io.connect('http://localhost:3000');
On the server side:
io.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
room = "abc123";
io.to(room).emit('message', 'what is going on, party people?');
});
});
You can not emit until you receive the connection.
You should instantiate a new instance of io, like so:
const socket = io();
Related
So, my program gets data from udp server and i just want to display it in list in HTML page 1 by 1 when it updates.
In console it works, but how to do it on page?
I got this code
index.js
var dgram = require('dgram'),
server = dgram.createSocket('udp4'); //this server gets data from udp packet
var msg;
server.on('message', function (message, rinfo) {
msg = message.toString('ascii'); //udp packet data to string
console.log(msg);
});
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening ' + address.address + ':' + address.port);
});
server.bind(8007);
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
var tm = setInterval(function() {
socket.emit('datafromserver', {'datafromserver': msg});
}, 500);
socket.on('disconnect', function() {
clearInterval(tm);
});
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and html page
<!doctype html>
<html>
<head>
<title>Scoreboard</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
</style>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io.connect('http://192.168.1.162:3000/');
socket.on('#dataonscreen', function(data) {
$('#dataonscreen').html(data.datafromserver);
console.log(data.datafromserver);
});
</script>
<ul id="dataonscreen"></ul>
</body>
</html>
I can't understand why this isn't working and how to fix it.
Please help!
Your socket.io server emits datafromserver while your code listens for #dataonscreen
Change either so that they are the same value and your code should work. I'm not sure how you have console output since the event is not being listened for
I've been trying to get familiarized with socket.io so use it in a real time app. I went through the basic example, a chat room, then I used ngrok to do a test with more than one client and it's all good. Now I'm looking to use TAFFY to save a log of the conversation on deploy it to a new user that connects to it so I added another emmit to send that log, and this particular emmit doesn't seem to ever trigger the on sentence in the client's side.
These are the server instructions
io.on('connection', function(socket){
console.log("someone connected");
var chatLog={log:[]};
log().each(function (iter){ //this is the taffy var
chatLog.log.push({"usr":iter.usr,"msg":iter.msg});
});
var stringLog=JSON.stringify(chatLog);
console.log(stringLog);
socket.emit('cargaLog', stringLog);// THIS is the naughty emmit
socket.on('chat message', function(msg){
var mensaje=JSON.parse(msg);
log.insert({"usr":mensaje.usr,
"msg":mensaje.msg
});
io.emit('chat message', mensaje.usr.toUpperCase()+" dice: "+mensaje.msg);
});
});
Client's side
$(function () {
var socket = io();
socket.on('cargaLog', function(log){
alert(log); //this never happens
console.log(log);
});
$('form').submit(function(){
var mensaje=$('#m').val();
var json='{"usr":"'+person+'","msg":"'+mensaje+'"}';
socket.emit('chat message', json);
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
var html='<li><img src="defaultUsrImg.png" alt="Usr_img" heigth="40" width="40">'+(msg)+'</li>';
$('#messages').append(html);
window.scrollTo(0, document.body.scrollHeight);
});
});
I've been staring at this code for a while and none of the solutions that worked with other people work for me (i.e. using io.connect() or io.connect('http://0.0.0.0:8080') on the client's side or having an emmit from the client that asks for the server emmit to be triggered).
Anyone has any idea why this happens?
Altenatively, anyone have any idea that could help me troubleshoot this better?
Other details are:
Running windows 10
Node version 8.2.1
socket.io version 2.0.3
This how I use the node requires:
var TAFFY = require('taffy');
var express=require('express');
var app = express();
var http = require('http');
var path=require('path');
var port = process.env.PORT || 3000;
var server= http.createServer(app).listen(port);
var io = require('socket.io').listen(server);
var log=TAFFY({"usr":"SERVER",
"msg":"WELCOME"
});
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
Client html code (only the boddy because mt html includes and it would bee way too long
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script type="text/javascript" src="./socket.io/socket.io.js"></script>
<script src="jquery-3.2.1.min.js"></script>
<!-- <script src="/mensajes.js"></script> THIS IS THE OLD CODE-->
<script >
var person = prompt("Introduce tu nombre o seudonimo", "anon"); //THIS IS THE WORKING CODE
if(person === null || person===""){
alert("Necesitas un nombre para participar");
}
else{
$(function () {
var socket = io();
socket.emit('ia iege',person);
socket.on('usrConectado',function(usr){
var html='<li><h6>'+(usr)+' se ha conectado</h6></li>';
$('#messages').append(html);
window.scrollTo(0, document.body.scrollHeight);
});
$('form').submit(function(){
var mensaje=$('#m').val();
var json='{"usr":"'+person+'","msg":"'+mensaje+'"}';
socket.emit('chat message', json);
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
var html='<li><img src="https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/419693/pedreiro-1500067445.PNG" alt="Usr_img" heigth="40" width="40">'+(msg)+'</li>';
$('#messages').append(html);
window.scrollTo(0, document.body.scrollHeight);
});
socket.on('cargaLog', function(log){
console.log(log);
var oldLog=JSON.parse(log);
cargaLog(oldLog);
});
});
function cargaLog(newLog){
//newLog is an object
newLog.log.forEach(function(iter){
var msg=iter.usr.toUpperCase()+' dijo: '+iter.msg;
var html='<li><img src="https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/419693/pedreiro-1500067445.PNG" alt="Usr_img" heigth="40" width="40">'+(msg)+'</li>';
$('#messages').append(html);
window.scrollTo(0, document.body.scrollHeight);
});
}
}
</script>
</body>
I reduced your code down to just the basics and I'm getting the message just fine that you were having trouble with. Here's the reduced code that works just fine:
Server code:
var express = require('express');
var app = express();
var http = require('http');
var path = require('path');
var port = process.env.PORT || 3000;
var server= http.createServer(app).listen(port);
var io = require('socket.io').listen(server);
app.get('/', function(req, res){
res.sendFile(__dirname + '/s1.html');
});
io.on('connection', function(socket) {
console.log("someone connected");
var chatLog = {log: [{usr: "someuser", msg: "somemsg"}]};
var stringLog = JSON.stringify(chatLog);
console.log(stringLog);
socket.emit('cargaLog', stringLog); // THIS is the naughty emmit
});
Client Code:
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script>
function dbg(x) {
let str = x;
if (typeof x === "object") {
str = JSON.stringify(x);
}
$("#log").append("<div>" + str + "</div>");
}
$(function() {
var socket = io();
socket.on('cargaLog', function(log) {
dbg(log);
});
});
</script>
</head>
<body>
Empty Content, waiting for message to arrive.
<div id="log"></div>
</body>
</html>
When I load the page, the browser immediately displays the cargaLog message that you were having trouble with. I would suggest that you backtrack to something super simple like this until you prove it works and then add things back one at a time until you find what is introducing the problem. If this code does not work for you, then you must have something goofed up in your environment and I'd probably do a reinstall of various components (socket.io, node.js, express, etc...).
Try
socket.emit('chat message' , { usr: person, msg: mensaje});
I think you can try to look at this repository https://github.com/egin10/socket-chat-example/blob/master/app.js for your server side.
and you can try this one for your client side https://github.com/egin10/socket-chat-example/blob/master/chat.html
Note: Just remember about socket.on(params, callback), it's for fetching data from emmiter, and io.emit(params, obj) on server side is for emmiting data.
so, you must make sure about what is your emmiting to server or client and what's your fetching (socket.on()) from serveror client must have same params.
and you must make sure about your object is var chatLog={log:[]};. if you want to get log, you must do like this chatLog.log.
It's work to me. i hope it can help you.
I have two clients which can interchange some data over socket.io. I also have a server. What i need to do is i want to send data from client 1 to client 2 over a socket and i am unable to figure out that how i can achieve it.Please note that client 1 and client 2 are different html pages.
Server.JS
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
var ip=process.env.IP||"192.168.1.5";
app.use(express.static(__dirname));
server.listen(port,ip, function () {
console.log('Server listening at port %d ', port);
});
app.get('/index', function(req, res) {
res.sendFile(path.join(__dirname,'/test.html'));
})
app.get('/index1', function(req, res) {
res.sendFile(path.join(__dirname,'/test1.html'));
})
io.on('connection', function (socket) {
socket.on('broadcast', function (message) {
console.log(message);
socket.broadcast.emit('message', message);
});
console.log("connected");
});
Client1.JS
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script >
var socket = io.connect();
socket.emit('broadcast',"Broadcasting Message");
socket.on('message', function (data) {
alert(data)
});
</script>
</body>
Client2.JS
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script >
var socket = io.connect();
socket.on('message', function (data) {
alert(data)
//socket.emit('message',"Hello world");
});
</script>
</body>
Ok, here is what I did on my local and you may change it by your needs.
server.js
var io = require('socket.io')(80);
io.on('connection', function (socket) {
socket.on('broadcast', function (message) {
console.log(message);
socket.broadcast.emit('message', message);
});
console.log("connected");
});
client1.js
var socket = io.connect('ws://127.0.0.1');
socket.emit('broadcast',"Broadcasting Message");
socket.on('message', function (data) {
$('#client1').html(data);
});
client2.js
var socket = io.connect('ws://127.0.0.1');
socket.on('message', function (data) {
$('#client2').html(data);
});
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src='https://code.jquery.com/jquery-1.12.4.min.js'></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="client1.js"></script>
<script type="text/javascript" src="client2.js"></script>
</head>
<body>
<div> <h1> CLIENT 1 </h1><div id="client1"></div></div>
<div> <h1> CLIENT 2 </h1><div id="client2"></div></div>
</body>
</html>
On a termminal after you run, node server.js and reload your page, you will see client2 will have Broadcasting message html appended
Make sure to pass the URL to the server when instantiating WS on the client side... for example var socket = io.connect('http://localhost');
On the server side, each WS connection with each client is a unique instance. That is to say that for this purpose you must be deliberate about which WS connection you target when emitting events.
The first thing to solve is how to associate WS connection instances with specific clients. The answer to this is to use a map/dictionary/plain ol' javascript object with some sort of unique client identifier as the key and the instance of the WS connection as the value. Pseudo-code:
let connections = { 'client1': WSinstance, 'client2': WSinstance };
You would add to this object every time you create a new WS instance. Assuming you have a way to uniquely identify a client and that is stored in the variable clientId, you could do the following:
io.on('connection', function (socket) {
connections[clientId] = socket;
}
Now if you want to emit a message to just client1 you can use the WS instance associated with them by grabbing it from the object connections.client1 or if you want to target client2 connections.client2
I am trying to use jQuery in my socket.io js (index.js) file.
Whenever I try to do
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="index.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('new user', function(data){
$('#newUserMessage').text(data);
});
</script>
I get this error in my console
GET http://localhost:3000/index.js
ReferenceError: $ is not defined
I'm not sure why this would happen?
But if I remove it I cant use jQuery's functions in index.js?
My index.js file
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var $usernameInput = $('.usernameInput');
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.broadcast.emit('new user', 'New User Joined, Say Hi :D');
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
function setUsername () {
username = cleanInput($usernameInput.val().trim());
if (username) {
socket.emit('add user', username);
}
}
You are a little confused, you have your front end and you have your back end.
Your index.js is your back end, you run that using NodeJS and you don't try to use jQuery on your back end, there's no DOM to manipulate. Also you don't include index.js on your front end, that's back end code.
This is wrong:
var $usernameInput = $('.usernameInput');
You can't access your DOM to get that value you have to send it to the back end, with some kind of event like this:
Front end
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chatMessage', $('#m').val());
$('#m').val('');
return false;
});
socket.on('connect', function(){
socket.emit('setUser', $('.usernameInput').val().trim());
});
socket.on('chatMessage', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('newUser', function(data){
$('#newUserMessage').text(data);
});
</script>
Back end
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.broadcast.emit('newUser', 'New User Joined, Say Hi :D');
socket.on('setUser', function(username){
console.log(username); //here you have your user name
});
socket.on('chatMessage', function(msg){
io.emit('chatMessage', msg);
});
});
Here is My code for socket IO
<script>
var socket = io.connect('<?php echo $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . ":8000" ?>');
console.log("tests" + socket);
socket.on('connect', function () {
});
socket.on('call_admin_notification', function (data) {
getAdminNotification();
});
</script>
I recently started using Socket.io, and node.js as a result, and I am kind of stuck. I do not even know if this is a practical solution for my application, but hopefully someone can help.
All I have here is a webpage with a checkbox, which reports it's status to the node console, and then when a TCP client connects, it receives the status as well.
I am wondering how I would go about making this event continuous, so that the TCP client constantly receives updates on the status of the checkbox.
If anyone has any idea, please let me know, and sorry for the long code...
Server Code:
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(http);
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
socket.write(MYVAR);
}).listen(PORT, HOST);
Client code:
<!doctype html>
<html>
<head>
<title>Socket IO Test</title>
<form action="">
<input type='checkbox' onclick='checkbox1(this);'>Checkbox1</label>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
var number = 0;
function checkbox1(cb) {
socket.emit('checkbox1', 'checkbox 1 = ' + cb.checked);
return false;
}
</script>
</body>
</html>
Cheers
I believe the issue here is that you don't have a way to reference the TCP socket. Once you do have a reference it is as easy as receiving a message and sending it.
This will work for a single client.
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(3000);
var s;
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
s.write(MYVAR, 'utf-8');
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
s = socket;
s.write(MYVAR, 'utf-8');
}).listen(PORT, HOST);
This will work for multiple clients.
var net = require('net');
var app = require('express')(); <!-- These are mandatory variables -->
var http = require('http').Server(app);
var io = require('socket.io')(3000);
var sockets = [];
var HOST = 'localhost';
var PORT = 4040;
GLOBAL.MYVAR = "Hello world";
var server = net.createServer();
server.listen(PORT, HOST);
app.get('/', function(req, res){ <!-- This sends the html file -->
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){ <!-- Tells the HTTP server which port to use -->
console.log('listening for HTTP on *:3001'); <!-- Outputs text to the console -->
console.log('listening for TCP on port ' + PORT);
});
<!-- everything below this line are actual commands for the actual app -->
io.on('connection', function(socket) // Opens the socket
{
socket.on('checkbox1', function(msg){ // Creates an event
console.log(msg); // displays the message in the console
MYVAR = msg; // Sets the global variable to be the contents of the message recieved
for (var i = 0; i < sockets.length; i++) {
if(sockets[i]) {
sockets[i].write(MYVAR, 'utf-8');
}
}
});
});
server.on('connection', function(socket){ // Opens the socket for the TCP connection
sockets.push(socket);
socket.write(MYVAR, 'utf-8');
}).listen(PORT, HOST);