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});
}
Related
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
I have no idea why this won't work; here's my code:
io.on('connection', function(socket) {
socket.on('join', function(data) {
socket.join(data.email); // We are using room of socket io
User.findById(bid.highestBidder, (err, theUser) => {
io.sockets.in(theUser.email).emit('outbid', {msg: 'You have been outbid!'});
});
});
});
Now, here's the code on the client-side javascript:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var userEmail = $("#userEmail").val();
socket.emit('join', {
email: userEmail
});
socket.on("outbid", function(data) {
console.log(data);
});
</script>
If you need me to paste more code, let me know and I will.
Basically, when the socket function gets executed, it's sending it to every browser instead of just the room with the "email."
io.on('connection', function(socket){
socket.join('room name');
});
io.to('room name').emit('some event');
So, I've been trying to write this chat-app for awhile now with Node.js, express,js and socket.io and everything works well. Apart from the fact that I'm trying to include a bot called Steve. Steves purpose is to welcome you to the chat, or to have him join after you've joined and introduce himself. As well as beeing able to reply to some "commands". Hi, How are you etc. Etc.
But that part is somethin that I can't get to work.
I'm not asking of you to write the code for me. But if you could please tell me if I'm on the right track and maybe come with some ideas, tips etc. I'm stuck.
Thanks in advance.
Here's my index.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.PORT || 3000);
console.log('Server running...');
app.use(express.static(__dirname + '/public'));
app.get('/public', function(req, res) {
res.sendFile(__dirname + 'index.html')
});
io.sockets.on('connection', function(socket) {
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
// Disconnect
socket.on('disconnect', function(data) {
users.splice(users.indexOf(socket.username), 1);
updateUsernames();
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: %s sockets connected', connections.length);
});
// Send Message
socket.on('send message', function(data) {
io.sockets.emit('new message', {msg: data, user: socket.username});
});
<code>
// New User
socket.on('new user', function(data, callback){
callback(true);
socket.username = data;
users.push(socket.username);
updateUsernames();
});
function updateUsernames() {
io.sockets.emit('get users', users);
}
});
And here's my script.js
$(function () {
var socket = io.connect();
var $messageForm = $('#messageForm');
var $message = $('#message');
var $chat = $('#chat');
var $messageArea = $('#messageArea');
var $userFormArea = $('#userFormArea');
var $userForm = $('#userForm');
var $users = $('#users');
var $username = $('#username');
var name = 'Steve', adress = 'localhost:3000', socket;
function join(){
socket.on('new user', name);
socket.emit('message', "Hi! I am Steve. Steve the Chatter!");
socket.on('new message', listener);
};
function listener(data){
if(data.message=='Hi')
socket.emit('message', 'Hi, '+$username+'.');
};
join();
$messageForm.submit(function(e) {
e.preventDefault();
socket.emit('send message', $message.val());
$message.val('');
});
socket.on('new message', function(data) {
$chat.append('<div class="well"><strong>'+data.user+'</strong>: '+data.msg+'</div>');
});
$userForm.submit(function(e) {
e.preventDefault();
socket.emit('new user', $username.val(), function(data) {
if(data) {
$userFormArea.hide();
$messageArea.show();
}
});
$username.val('');
});
socket.on('get users', function(data) {
var html = '';
for(i = 0;i < data.length;i++){
html += '<li class="list-group-item">'+data[i]+'</li>'
;
}
$users.html(html);
});
});
I have a simple client server web app that is using web sockets to send / receive information. The client can connect and receives properly the config file but then when I try to send a "test' message from the client using "socket.emit('message', {my: 'data'});" it doesn't display on the server. I did check with wireshark and the packets are arriving at the server.
var sIoPort = 8181;
var host = '192.168.4.111';
var fs = require('fs');
var iniMsg = fs.readFileSync('data.json','utf8');
var http = require("http").createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
http.listen(sIoPort,host);
var browserServer = require('socket.io').listen(http);
browserServer.on('connection', function (socket) {
console.log('Client websocket connected');
// send the config file if available
browserServer.sockets.emit('msg',iniMsg.toString());
});
browserServer.on('message', function (message) {
console.log('received message: ' + message);
});
client side
///////////////////////////////////////////////////////////////////////////////
socket = io.connect("192.168.4.111",{"port":8181});
socket.on('connect',function() {if(DEBUG) console.log('Socket Connected');});
socket.emit('message', {my: 'data'}); // test if server receives message
socket.on('msg',function(data) {
var json = JSON.parse(data);
// add the maps to the the GUI
switch(json.type) {
case 'maps': add_maps_from_json(json, null);
break;
}
});
socket.on('disconnect',function() {if(DEBUG) console.log('Socket Disconnected');});
/////////////////////////////////////////////////////////////////////////////////
Modify the serverside listener so it's paying attention to events on a socket:
browserServer.on('connection', function (socket) {
console.log('Client websocket connected');
// send the config file if available
browserServer.sockets.emit('msg',iniMsg.toString());
socket.on('message', function (message) {
console.log('received message: ' + message);
});
});
I have this code running in
Client side:
$(function(){
var iosocket = io.connect();
iosocket.on('connect', function () {
$('#incomingChatMessages').append($('<li>Connected</li>'));
iosocket.on('message', function(message) {
$('#incomingChatMessages').append($('<li></li>').text(message));
});
iosocket.on('disconnect', function() {
$('#incomingChatMessages').append('<li>Disconnected</li>');
});
});
$('#outgoingChatMessage').keypress(function(event) {
if(event.which == 13) {
event.preventDefault();
iosocket.send($('#outgoingChatMessage').val());
$('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val()));
$('#outgoingChatMessage').val('');
}
});
});
Server Side
var fs = require('fs'), http = require('http'), socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(8080, function() {
console.log('Listening at: localhost');
});
socketio.listen(server).on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
Question :
How can I include the getUserMedia and other WEBRTC API's to create a simple video application ?
Have you looked at, or found, an opensource code set named webrtc.io. If you look at the example code (in the webrtc.io-demo project), you will find a really good example of how to use the getusermedia and peerconnection API's. This code does implement node.js but websocket.io instead of socket.io. I do not know that much about either, so I am not sure if there exists any compatibility between them.