The chat is programmed in nodejs using websockets from socket.io library and i have a client that also uses websockets from socket.io but I don't manage to make the two work together. For some reason the client doesn't send the message to the server (I have a console.log function that should write to console when it receives a message but it doesn't write anything).
The code for the server is:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
io.emit('chat message', msg);
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
And for the client is :
<!DOCTYPE html>
<html>
<head>
<style>
* { margin:0; padding:0; font-size:11px; font-family:arial; color:#444; }
body { padding:20px; }
#message-list { list-style-type:none; width:300px; height:300px; overflow:auto; border:1px solid #999; padding:20px; }
#message-list li { border-bottom:1px solid #ccc; padding-bottom:2px; margin-bottom:5px; }
code { font-family:courier; background:#eee; padding:2px 4px; }
</style>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
}
// Outputs to console and list
function log(message) {
var li = document.createElement('li');
li.innerHTML = message;
document.getElementById('message-list').appendChild(li);
}
// Create a socket instance
socket = new WebSocket('ws://localhost:8080');
// Open the socket
socket.onopen = function(event) {
console.log('Socket opened on client side',event);
// Listen for messages
socket.onmessage = function(event) {
console.log('Client received a message',event);
};
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
};
</script>
</head>
<body>
<p>Messages will appear below (and in the console).</p><br />
<ul id="message-list"></ul>
<ul style="margin:20px 0 0 20px;">
<li>Type <code>socket.disconnect()</code> to disconnect</li>
<li>Type <code>socket.connect()</code> to reconnect</li>
<li>Type <code>sendMessageToServer('Your Message')</code> to send a message to the server</li>
</ul>
</body>
</html>
Do you have any idea what is wrong here?
Thanks in advance!
You have a couple issues based on my knowledge. If they are all fixed, it should work.
The connection socket.io.js file should be your own one. In your case, I am guessing it is <script src="http://localhost:3000/socket/socket.io.js"></script> I am not 100 percent sure because your port could vary.
You didn't define socket properly on your client side. Define it as this: var socket = io();. The way you did it is socket = new WebSocket('ws://localhost:8080'); Where WebSocket is not defined. And, the code will create a new websocket server, which you already did in your server code. What you need to do at client side is only connect to the server.
You must use the same channel to let the client and server to communicate. So in your client code, you should send message like this socket.emit('chat message', 'content you want to send'.
I don't know why you emit the message at server side again BTW. I am assuming you are sending message from client to server. So you shouldn't have emit command in your server code.
If all the four things been fixed, it will work.
In case my expression is not clear, I wrote a super simple example for you:
Server side:
let io = socketio(server.listener);
io.on("connection", function(socket) {
console.log("A user connected");
// auto messages when a user is connected
setTimeout(function() {
socket.send("message at 4 seconds");
}, 4000);
setTimeout(function() {
socket.send("message at 8 seconds");
}, 8000);
// callback when a user disconnected
socket.on("disconnect", function(){
console.log("A user disconnected");
});
// receive message from client
socket.on("client-server", function(msg) {
console.log(msg);
});
});
// you put this code anywhere when you need to send message from server to client
io.emit("server-client", "server to client message");
Client side:
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('server-client', function(data) {document.write(data)});
socket.emit('client-server', 'test message');
</script>
<body>Hello world</body>
</html>
My server code is written in typescript so never mind the let key word, double quote and so on.
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
My SocketIO server returns a count of 10 to 0 every second, but my web page only updates the number every 10-15 seconds. However, my NodeJS console well displays this count.
In addition, when I manually reload my web page, my browser shows me the correct figure, but suddenly I have to wait 10-15 seconds for it to display the next digit.
NodeJS part
var http = require('http');
var fs = require('fs');
require('events').EventEmitter.prototype._maxListeners = 100;
var server = http.createServer(function(req, res) {
fs.readFile('./serv.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
function envoi(p1){
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('message', p1);
});
}
main();
function main(){
var interval = setInterval(loop, 1000);
var a = 10;
function loop(){
if(a<1){
clearInterval(interval);
rolling();
}
else{
console.log(a);
a--;
envoi(a);
}
}
}
function rolling(){
console.log('ok');
main();
}
server.listen(8080);
HTML/JS part
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Communication avec socket.io !</h1>
<div id='r'>Connection..</div>
<script src="jquery.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('message', function(message) {
document.getElementById('r').innerHTML = message;
})
</script>
</body>
</html>
Thank you :)
Nathan
There are a few problem with your server side socket.io code that could be causing issues.
Your envoi function is creating a new socket.io server in every loop execution. It is probably returning a cached version, but, you should only invoke listen once. Similar to how creating your http server operates. It should ideally follow your http server creation.
In the same vein, you should only register to the connection event once following your call to listen. You should then store the connected socket somewhere or use the io.socket property to retrieve connected sockets.
Your code that prints down the number should look something like this
let val = 10;
function pushNumber() {
io.sockets.emit('message', val); // Sends message to all sockets on default namespace
val--;
}
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 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);
I have multiple buttons with an attribute called groupName. They look like this:
SCENE I
SCENE II
SCENE III
I'm trying to figure out how to get socket.io to emit the link's groupName value when clicked. So when the first link is clicked, socket.io would emit "groupName - SCENE_I"
How could this be accomplished?
It seems you want something similar to a chat -- where a click on a link acts as a user sending a message to the server, and the server would emit that to a room (to other users, I suppose?)
If that's the case, you should take a look at this example: http://socket.io/get-started/chat/
You would do something like this on the client side:
<html>
<head>
</head>
<body>
SCENE I
SCENE II
SCENE III
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
$(document).ready(function(){
var socket = io();
// listen to server events related to messages coming from other users. Call this event "newClick"
socket.on('newClick', function(msg){
console.log("got new click: " + msg);
});
// when clicked, do some action
$('.fireGroup').on('click', function(){
var linkClicked = 'groupName - ' + $(this).attr('groupName');
console.log(linkClicked);
// emit from client to server
socket.emit('linkClicked', linkClicked);
return false;
});
});
</script>
</body>
</html>
On the server side, still taking the chat idea into consideration:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('./index.html');
});
io.on('connection', function(socket){
// when linkClicked received from client...
socket.on('linkClicked', function(msg){
console.log("msg: " + msg);
// broadcast to all other users -- originating client does not receive this message.
// to see it, open another browser window
socket.broadcast.emit('newClick', 'Someone clicked ' + msg) // attention: this is a general broadcas -- check how to emit to a room
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});