I am currently building a game using Socket.IO and Javascript. I originally wanted to make a real-time multiplayer game, however, I ran into a problem really quick. I eventually gave up and moved to a turn-based game but the problem still didn't go away.
The problem is that the server (app.js) is not getting emits from the client (game.js). I've tried recreating the project, console.log, and search google to no avail.
App.js
require('./Database');
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
serv.listen(process.env.PORT || 2000);
console.log("Server started.");
var SOCKET_LIST = {};
var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket) {
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
socket.on('signIn', function(data) { // {username,password}
Database.isValidPassword(data, function(res) {
if (!res)
return socket.emit('signInResponse', { success: false });
Database.getPlayerProgress(data.username, function (progress) {
socket.emit('signInResponse', {
success: true, username: data.username,
progress: progress
});
})
});
});
socket.on('signUp', function(data) {
Database.isUsernameTaken(data, function(res) {
if (res) {
socket.emit('signUpResponse', { success: false });
} else {
Database.addUser(data, function() {
socket.emit('signUpResponse', { success: true });
});
}
});
});
socket.on('disconnect', function() {
delete SOCKET_LIST[socket.id];
});
socket.on("findMatch", function(data) {
console.log('test'); // ******* Not working ********
});
});
Game.js
var socket = io("127.0.0.1:2000");
function findMatch(data) {
socket.emit("findMatch", { socket: socket });
}
FindMatch() is called from the lobby "Find Match" Button. It is hooked up to an onclick listener.
Thank you. I would appreciate any help.
Edit: The connection, sign In, register, and disconnect emits DO work only custom ones I add later (findMatch for example) don't work
Related
I'll try to make this as simple as possible so i'm not having to post a ton of code. Heres what my app does right now:
User uploads an audio file from the browser
That file is processed on my server, this process takes some time and has about 8 or so steps to complete.
Once everything is finished, the user gets feedback in the browser that the process is complete.
What I want to add to this, is after every step in the process that is completed, send some data back to the server. For example: "Your file is uploaded", "Meta data processed", "image extracted" etc etc so the user gets incremental feedback about what is happening and I believe Server Sent Events can help me do this.
Currently, the file is POSTed to the server with app.post('/api/track', upload.single('track'), audio.process). audio.process is where all the magic happens and sends the data back to the browser with res.send(). Pretty typical.
While trying to get the events working, I have implemented this function
app.get('/stream', function(req, res) {
res.sseSetup()
for (var i = 0; i < 5; i++) {
res.sseSend({count: i})
}
})
and when the user uploads a file from the server I just make a call to this route and register all the necessary events with this function on the client side:
progress : () => {
if (!!window.EventSource) {
const source = new EventSource('/stream')
source.addEventListener('message', function(e) {
let data = JSON.parse(e.data)
console.log(e);
}, false)
source.addEventListener('open', function(e) {
console.log("Connected to /stream");
}, false)
source.addEventListener('error', function(e) {
if (e.target.readyState == EventSource.CLOSED) {
console.log("Disconnected from /stream");
} else if (e.target.readyState == EventSource.CONNECTING) {
console.log('Connecting to /stream');
}
}, false)
} else {
console.log("Your browser doesn't support SSE")
}
}
this works as expected, when I upload a track, i get a stream of events counting from 0-4. So thats great!
My Problem/Question: How do i send relevant messages from the audio.process route, to the /stream route so that the messages can be related to whats happening. audio.process has to be a POST, and /stream has to be a GET with the header 'Content-Type': 'text/event-stream'. It seems kind of weird to make GET requests from within audio.process but is this the best way?
Any and all advice/tips are appreciated! Let me know if you need any more info.
New Answer:
Just use socket.io, it's so much easier and better!
https://www.npmjs.com/package/socket.io#in-conjunction-with-express
basic setup:
const express = require('express');
const PORT = process.env.PORT || 5000;
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
// listen to socket connections
io.on('connection', function(socket){
// get that socket and listen to events
socket.on('chat message', function(msg){
// emit data from the server
io.emit('chat message', msg);
});
});
// Tip: add the `io` reference to the request object through a middleware like so:
app.use(function(request, response, next){
request.io = io;
next();
});
server.listen(PORT);
console.log(`Listening on port ${PORT}...`);
and in any route handler, you can use socket.io:
app.post('/post/:post_id/like/:user_id', function likePost(request, response) {
//...
request.io.emit('action', 'user liked your post');
})
client side:
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
full example: https://socket.io/get-started/chat/
Original Answer
Someone (user: https://stackoverflow.com/users/451634/benny-neugebauer | from this article: addEventListener on custom object) literally gave me a hint on how to implement this without any other package except express! I have it working!
First, import Node's EventEmitter:
const EventEmitter = require('events');
Then create an instance:
const Stream = new EventEmitter();
Then create a GET route for event streaming:
app.get('/stream', function(request, response){
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
Stream.on("push", function(event, data) {
response.write("event: " + String(event) + "\n" + "data: " + JSON.stringify(data) + "\n\n");
});
});
In this GET route, you are writing back that the request is 200 OK, content-type is text/event-stream, no cache, and to keep-alive.
You are also going to call the .on method of your EventEmitter instance, which takes 2 parameters: a string of the event to listen for and a function to handle that event(that function can take as much params as it is given)
Now.... all you have to do to send a server event is to call the .emit method of your EventEmitter instance:
Stream.emit("push", "test", { msg: "admit one" });
The first parameter is a string of the event you want to trigger (make sure that it is the same as the one in the GET route). Every subsequent parameter to the .emit method will be passed to the listener's callback!
That is it!
Since your instance was defined in a scope above your route definitions, you can call the .emit method from any other route:
app.get('/', function(request, response){
Stream.emit("push", "test", { msg: "admit one" });
response.render("welcome.html", {});
});
Thanks to how JavaScript scoping works, you can even pass that EventEmitter instance around to other function, even from other modules:
const someModule = require('./someModule');
app.get('/', function(request, response){
someModule.someMethod(request, Stream)
.then(obj => { return response.json({}) });
});
In someModule:
function someMethod(request, Stream) {
return new Promise((resolve, reject) => {
Stream.emit("push", "test", { data: 'some data' });
return resolve();
})
}
That easy! No other package needed!
Here is a link to Node's EventEmitter Class: https://nodejs.org/api/events.html#events_class_eventemitter
My example:
const EventEmitter = require('events');
const express = require('express');
const app = express();
const Stream = new EventEmitter(); // my event emitter instance
app.get('/stream', function(request, response){
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
Stream.on("push", function(event, data) {
response.write("event: " + String(event) + "\n" + "data: " + JSON.stringify(data) + "\n\n");
});
});
setInterval(function(){
Stream.emit("push", "test", { msg: "admit one" });
}, 10000)
UPDATE:
i created a module/file that is easier to use and doesn't cause memory leaks!
const Stream = function() {
var self = this;
// object literal of connections; IP addresses as the key
self.connections = {};
self.enable = function() {
return function(req, res, next) {
res.sseSetup = function() {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
}
res.sseSend = function(id, event, data) {
var stream = "id: " + String(id) + "\n" +
"event: " + String(event) + "\n" +
"data: " + JSON.stringify(data) +
"\n\n";
// console.log(id, event, data, stream);
res.write(stream);
}
next()
}
}
self.add = function(request, response) {
response.sseSetup();
var ip = String(request.ip);
self.connections[ip] = response;
}.bind(self);
self.push_sse = function(id, type, obj) {
Object.keys(self.connections).forEach(function(key){
self.connections[key].sseSend(id, type, obj);
});
}.bind(self);
}
/*
Usage:
---
const express = require('express');
const Stream = require('./express-eventstream');
const app = express();
const stream = new Stream();
app.use(stream.enable());
app.get('/stream', function(request, response) {
stream.add(request, response);
stream.push_sse(1, "opened", { msg: 'connection opened!' });
});
app.get('/test_route', function(request, response){
stream.push_sse(2, "new_event", { event: true });
return response.json({ msg: 'admit one' });
});
*/
module.exports = Stream;
Script located here - https://github.com/ryanwaite28/script-store/blob/master/js/express-eventstream.js
when users online and don't close our clients such as browser tab or android application, i can send message to each specific user by
socket.broadcast.to(socketId)
.emit('new message', {
username: data.fromUsername,
money : 'Hurrraaa'
});
when users close clients as mobile application this event don't trigger but i can send any message to broadcast as:
socket.broadcast.emit('new message', "hooooorrrrraaaaa");
my users don't use client application any time, but i need to send message to some specific user and notify user until opening application and see message, users should be on'time in my application to get every message which i want to send from server like with Chat messengers which don't need users currently are using application such as WhatsApp, how can i resolve this problem?
then problem is send message to some specific users when they are istalled application and logged ti sever, but not using now and application waiting to receive message such as broadcast or special message to himself
this code is my simplified server:
var socket = require('socket.io'),
express = require('express'),
app = express(),
server = require('http').createServer(app),
io = socket.listen(server),
port = process.env.PORT || 3000,
mysql = require('mysql'),
uuid = require('node-uuid'),
datetime = require('node-datetime'),
moment = require('moment'),
bcrypt = require('bcrypt'),
async = require('async'),
request = require('request'),
redis = require("redis"),
redisClient = redis.createClient(),
forever = require('forever'),
log = require('log4node');
var io_redis = require('socket.io-redis');
io.adapter(io_redis({host: 'localhost', port: 6379}));
require('sticky-socket-cluster/replace-console')();
var options = {
workers : require('os').cpus().length,
first_port : 8000,
proxy_port : 3000,
session_hash: function (req, res) {
return req.connection.remoteAddress;
},
no_sockets: false
};
require('sticky-socket-cluster')(options, start);
function start(port) {
io.sockets.on('connection', function (socket) {
socket.on('new message', function (data) {
socket.broadcast.emit('new message', "hooooorrrrraaaaa");
});
socket.on('login', function (data) {
log.info(JSON.stringify(data))
login(data.username, data.password, function (success, value) {
if (success) {
redisClient.exists(data.username, function (err, doesExist) {
if (err) return;
if (!doesExist) {
redisClient.set(data.username, socket.id, function (err, res) {
redisClient.set(data.username, socket.id);
});
}
else {
redisClient.del(data.username);
redisClient.set(data.username, socket.id, function (err, res) {
redisClient.set(data.username, socket.id);
});
}
});
socket.emit('login', {
result : true,
id : value.id,
registeredMobileNumber: value.registeredMobileNumber
});
} else {
socket.emit('login', {result: false});
}
});
});
socket.on('userConnected', function (username) {
redisClient.exists(username, function (err, doesExist) {
if (err) return;
if (!doesExist) {
redisClient.set(username, socket.id, function (err, res) {
redisClient.set(username, socket.id);
});
}
else {
redisClient.del(username);
redisClient.set(username, socket.id, function (err, res) {
redisClient.set(username, socket.id);
});
}
});
});
socket.on('disconnectUser', function (data) {
redisClient.exists(data.username, function (err, doesExist) {
if (err) return;
if (doesExist) {
redisClient.del(data.username);
}
});
});
server.listen(port, function () {
console.log('Express and socket.io listening on port ' + port);
});
}
You can use socket.on('disconnect', function() {});
When a User disconnects , save the users user_id.
Subsequent message on the user_id would be saved in the server.
When the client reconnects again get the time of the latest message and then push the message after that time (saved in the server) to the client.
I have two major js files, one on the server side which is the server.js and another on the client side, which is enterchat.js. These two files are the ones which will communicate via socket.io. All socket events are working as expected.
server.js
var express = require('express'),
...
server = require('http').createServer(app),
io = require('socket.io').listen(server);
var usernames = [],
username_sockets = [];
...
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use('/', express.static(__dirname+'/public/'));
app.get('/chat', function (req, res) {
res.render('checkUsername', {title:'Socket IO Chat'});
});
app.get('/chatwindow', function (req, res) {
res.render('chatwindow', {title:'Welcome to chat window'});
});
io.sockets.on('connection', function (socket) {
socket.on('disconnect', function () {
...
delete username_sockets[socket.id];
console.log("Disconnected from " + user);
});
socket.on('newusr', function (newusrname) {
console.log("New user name request:: " + newusrname);
if(usernames.indexOf(newusrname) >= 0)
{
console.log("Already used username..");
socket.emit('usernameTaken', newusrname);
}
else
{
socket.emit('usernameavlbl', newusrname);
}
});
socket.on('startchat', function (usernameAvailable) {
if(usernames.indexOf(usernameAvailable) >= 0)
{
console.log("Just taken username..");
socket.emit('usernameJustTaken', usernameAvailable); //returning the username that was just taken
}
else
{
usernames.push(usernameAvailable);
console.log("Opening chat window for "+usernameAvailable);
username_sockets[socket.id] = usernameAvailable;
// trying to render jade view to open chatwindow on socket event
}
});
socket.on('sndmsg', function (message) {
socket.broadcast.emit('msgreceive', message, username_sockets[socket.id]);
});
socket.on('typing', function (username) {
socket.broadcast.emit('usertyping', username);
});
socket.on('stoppedtyping', function (username) {
socket.broadcast.emit('userstoppedtyping', username);
});
});
server.listen(8080,'0.0.0.0');
console.log("Listening on 8080..");
enterchat.js
var socket, usernameAvailable;
$(document).ready(function () {
connect();
...
...
$('#checkBtn').on('click', function(event) {
if($('#username').val() == '')
alert("Choose a username");
else
{
var newusrname = $('#username').val();
socket.emit('newusr', newusrname);
}
});
...
socket.on('usernameTaken', function (message) {
alert(message + " is already taken. Try another one..");
});
socket.on('usernameJustTaken', function (message) {
alert(message + " was just taken. Try another one..");
});
socket.on('usernameavlbl', function (newusrname) {
$('#chataway').attr('disabled', false);
usernameAvailable = newusrname;
});
$('#chataway').on('click', function () {
socket.emit('startchat', usernameAvailable);
});
});
function connect () {
socket = io.connect(null);
}
My question: How do I render the chatwindow view upon the socket event startchat?
I looked at this question: In Express.js, how can I render a Jade partial-view without a "response" object?, but I am not sure as to how to add it in my code so that a fresh jade view (chatwindow) is loaded on the browser.
You can use compileFile method of jade api, get the html and then emit a socket event containing the html data. You can append that html to the DOM.
socket.on('startchat', function (usernameAvailable) {
if(usernames.indexOf(usernameAvailable) >= 0)
{
console.log("Just taken username..");
socket.emit('usernameJustTaken', usernameAvailable); //returning the username that was just taken
}
else
{
usernames.push(usernameAvailable);
console.log("Opening chat window for "+usernameAvailable);
username_sockets[socket.id] = usernameAvailable;
var fn = jade.compileFile('path to jade file', options);
// Render function
var html = fn();
// Now you can send this html to the client by emitting a socket event
}
});
Heya I'm trying to build a small chat client to learn how websockets work in order to make a game in canvas. It works great with sending sockets but they are only sending it to the the one who wrote it.
I guess I've missed something small, but I can't understand why it won't work.
Server side code
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('user-message', function (data) {
console.log(data);
sendMessage(data.message);
});
});
var sendMessage = function(message) {
io.sockets.emit('server-message', {message: message});
}
Client side code
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('server-message', function (data) {
var history = $('#chatbox').val();
$('#chatbox').val(history + "\n" + data.message)
});
$("#write").keyup(function(event){
if(event.keyCode == 13){
socket.emit('user-message', {message: $(this).val()});
$(this).val('');
}
});
</script>
You can use socket.broadcast.emit to send a message to all other sockets.
io.sockets.on('connection', function (socket) {
socket.on('user-message', function (data) {
console.log(data);
sendMessage.call(socket, data.message);
});
});
var sendMessage = function(message) {
this.emit('server-message', {message: message});
this.broadcast.emit('server-message', {message: message});
}
I'm trying to use cookie based sessions, however it'll only work on the local machine, not over the network. If I remove the session related stuff, it will however work just great over the network...
You'll have to forgive the lack of quality code here, I'm just starting out with node/socket etc etc, and finding any clear guides is tough going, so I'm in n00b territory right now. Basically this is so far hacked together from various snippets with about 10% understanding of what I'm actually doing...
The error I see in Chrome is:
socket.io.js:1632GET http://192.168.0.6:8080/socket.io/1/?t=1334431940273 500 (Internal Server Error)
Socket.handshake ------- socket.io.js:1632
Socket.connect ------- socket.io.js:1671
Socket ------- socket.io.js:1530
io.connect ------- socket.io.js:91
(anonymous function) ------- /socket-test/:9
jQuery.extend.ready ------- jquery.js:438
And in the console for the server I see:
debug - served static content /socket.io.js
debug - authorized
warn - handshake error No cookie
My server is:
var express = require('express')
, app = express.createServer()
, io = require('socket.io').listen(app)
, connect = require('express/node_modules/connect')
, parseCookie = connect.utils.parseCookie
, RedisStore = require('connect-redis')(express)
, sessionStore = new RedisStore();
app.listen(8080, '192.168.0.6');
app.configure(function()
{
app.use(express.cookieParser());
app.use(express.session(
{
secret: 'YOURSOOPERSEKRITKEY',
store: sessionStore
}));
});
io.configure(function()
{
io.set('authorization', function(data, callback)
{
if(data.headers.cookie)
{
var cookie = parseCookie(data.headers.cookie);
sessionStore.get(cookie['connect.sid'], function(err, session)
{
if(err || !session)
{
callback('Error', false);
}
else
{
data.session = session;
callback(null, true);
}
});
}
else
{
callback('No cookie', false);
}
});
});
var users_count = 0;
io.sockets.on('connection', function (socket)
{
console.log('New Connection');
var session = socket.handshake.session;
++users_count;
io.sockets.emit('users_count', users_count);
socket.on('something', function(data)
{
io.sockets.emit('doing_something', data['data']);
});
socket.on('disconnect', function()
{
--users_count;
io.sockets.emit('users_count', users_count);
});
});
My page JS is:
jQuery(function($){
var socket = io.connect('http://192.168.0.6', { port: 8080 } );
socket.on('users_count', function(data)
{
$('#client_count').text(data);
});
socket.on('doing_something', function(data)
{
if(data == '')
{
window.setTimeout(function()
{
$('#target').text(data);
}, 3000);
}
else
{
$('#target').text(data);
}
});
$('#textbox').keydown(function()
{
socket.emit('something', { data: 'typing' });
});
$('#textbox').keyup(function()
{
socket.emit('something', { data: '' });
});
});
Check your system clock, if the server and client have different clocks, the cookie may be immediately expiring right after you set it.