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);
});
});
Related
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');
I have a socket.io app that works perfectly on chrome, safari and opera, with notifications made using push.js.
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://cdn.rawgit.com/Nickersoft/push.js/master/push.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var socket = io();
var username = prompt("What's your name?");
var notification = new Audio('https://cdn.rawgit.com/InfiniaPress/Passenger-Pigeon/master/assets/notification.mp3');
if(username){
socket.emit('connection info', username);
}
function send(message) {
$('#messages').append($('<li>').text(message));
}
socket.on('user add', function(usr){
send(usr.username + " has joined.");
});
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('user left', function(usr){
send(usr.username + " has disconnected.");
})
socket.on('chat message', function(msg, usr){
Push.create('Passenger Pigeon', {
body: usr.username + ": " + msg,
icon: "https://cdn.rawgit.com/InfiniaPress/Passenger-Pigeon/master/assets/pigeon-final.png",
timeout: 4000,
onClick: function () {
window.focus();
this.close();
},
vibrate: [200, 100, 200, 100, 200, 100, 200]
});
notification.play();
send(usr.username + ": " + msg);
});
</script>
</body>
</html>
The above is my client side.
var express = require('express'); // Get the module
var app = express(); // Create express by calling the prototype in var express
var http = require('http').Server(app);
var io = require('socket.io')(http);
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
var config = require('./config.json');
app.get('/', function(req, res){
res.sendFile(__dirname + '/view/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg, {username: socket.username});
});
socket.on('connection info', function(usr){
socket.username = usr;
io.emit('user add', {username: usr});
});
});
io.on('connection', function(socket){
console.log('Passenger Pigeon >> a user connected');
socket.on('disconnect', function(){
socket.broadcast.emit('user left', {
username: socket.username,
});
console.log('Passenger Pigeon >> user disconnected');
});
});
http.listen(process.env.PORT || config.port, function(){
console.log('listening on *:' + config.port);
});
^that is my server side.
When I open the app on mobile the [username] has joined prints out, but all messages do NOT appear on the client side. Other computers receive the messages. Why is this so?
I want to write a simple chat for practical experience.
All right, but I can't get a socket.nickname for notice a join/leave from the room. (when I tried pass its, he always sad a 'undefined').
Now all right, tried to create list of rooms
UPDATE CODE:
client.js:
$('#roomForm').submit(function() {
socket.emit('createRoom', $('#roomName').val());
$('#roomForm').hide();
$('#chatForm').show();
return false;
});
socket.on('message', function(data) {
newMessage(data);
});
socket.on('showRooms', function(rooms) {
console.log(rooms);
for(var i = 0; i < rooms.length; i++) {
$('#rooms').append($('<li>')
.append($('<form id="freeRoom">')
.append($('<span id="room">').text(rooms[i] + ' ///'))
.append($('<button>').text('connect'))));
};
});
$('#freeRoom').submit(function() {
socket.emit('connectToRoom', $('#room').text());
return false;
});
server.js:
io.on('connection', function(socket) {
socket.on('sendNickname', function(username) {
socket.username = username;
users.push(socket.username);
socket.emit('showRooms', rooms);
});
socket.on('disconnect', function() {
socket.broadcast.to(socket.room).emit('notice', socket.username + ' has left the room');
users.splice(users.indexOf(socket.username), 1);
socket.emit('showRooms', rooms);
});
socket.on('message', function(data) {
socket.broadcast.to(socket.room).emit('message', data);
});
socket.on('createRoom', function(room) {
socket.leave(socket.room);
socket.room = room;
rooms.push(socket.room);
socket.join(socket.room);
socket.emit('showRooms', rooms);
console.log('Rooms: ' + rooms);
socket.broadcast.to(socket.room).emit('notice', socket.username + ' has joined to room');
});
socket.on('connectToRoom', function(room) {
console.log('Will connect to that room: ' + room);
socket.join(room);
});
});
**UPD 2: **
Tried to connect free created room:
$('#freeRoom').submit(function() {
socket.emit('connectToRoom', $('#room').text());
return false;
});
P.S. And... Sorry for my english >.<
The event name that you emit, that is 'connect' is reserved in Socket.io along with 'message' and 'disconnect':
http://socket.io/docs/#sending-and-receiving-events
Socket.IO allows you to emit and receive custom events. Besides
connect, message and disconnect, you can emit custom events:
...
Change it to something else, e.g:
Server.js:
io.on('connection', function(socket) {
socket.on('send-nickname', function(nickname) {
socket.nickname = nickname;
users.push(socket.nickname);
console.log(users);
});
...
Client.js
socket.emit('send-nickname', nickname);
I am trying to connect 2 users in 1 room and exchange some data, how can i do that? when i accessing the server getting only : abba
server.js:
var http = require('http');
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('abba');
});
var io = require('socket.io').listen(app);
var messageExchange = io
.of('/play')
.on('connection', function (socket) {
socket.channel = "";
socket.on("joinChannel", function (data) {
socket.channel = data.channel;
});
socket.on("message", function (data) {
socket.broadcast.emit("message", {
channel: socket.channel,
message: data.message
});
});
});
app.listen(3000);
client:
<script>
var chat = io.connect('//talk.test.com:3000/play');
var channel = "ciao";
chat.on("connect", function () {
chat.emit("joinChannel", {
channel: channel
});
});
chat.on("message", function (data) {
if (data.channel == channel) {
alert(data.message);
}
});
// Send a message!
chat.emit("message", { message: "hola" });
</script>
Step 1 - run this in server
$ cat server.js
var io = require('socket.io').listen(3000);
io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone'});
socket.on('joinChannel', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
io.sockets.emit('message', {channel: from.channel, message: 'Got it?' } );
});
socket.on('disconnect', function () {
io.sockets.emit('disconnected');
});
});
$ node server.js
Step 2: make an index.html with following:
<?php
$room = $_GET['r'];
?>
<!doctype html>
<html>
<head>
<script src='//code.jquery.com/jquery-1.7.2.min.js'></script>
<script src='//talk.domain.com:3000/socket.io/socket.io.js'></script>
<script>
var chat = io.connect('//talk.domain.com:3000');
var channel = '<?php echo $room;?>';
chat.on("connect", function () {
chat.emit("joinChannel", {
channel: channel,
message: 'OKOKOKOKOKOK'
});
});
chat.on("message", function (data) {
if (data.channel == channel) {
alert(data.message);
}
});
</script>
</head>
<body>
</body>
</html>
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});
}