I have a simple app running on docker container. This container is not running all the time. It starts, does certain job and stops. When it is up, I would like to connect it to a server via socket.io. I have tried to use socket.io-client but still unable to make it works. This is my app code:
var docker_host_ip = process.env.DOCKER_HOST_IP;
var address = 'http://' + docker_host_ip +":" + port;
console.log("console : " + address);
var socket = require('socket.io-client')(address);
socket.on("disconnect", function(){
console.log("disconnected ");
});
socket.on("connect_failed", function(err){
console.log("err : " + err);
});
socket.on('connect', function(){
console.log("connected");
});
socket.on('news', function(data){
console.log("data : " + data);
socket.emit("news", {docker: "This is docker"});
});
socket.emit("news", {docker: "This is docker"});
socket.on('error', function (err) {
console.log(err);
});
I used this https://github.com/socketio/socket.io-client.
var port = 4000;
app.use(express.static('.'))
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
socket.emit("news", {"hello": "hello"});
socket.on("news", function(data){
console.log( "new " + data);
io.sockets.emit("news", data);
});
socket.on('disconnect', function() {
console.log('Got disconnect!');
});
});
app.get("/", function(res, req){
req.sendFile(path.join('/index.html'));
});
http.listen(port, function(){
console.log('listening on *' + port);
});
My app is not showing any error, but not message is sent. My server is working correctly through browser (with socket.io).
Can someone please tell me what is wrong ?
You have two same socket.emit message names, I guess the server send the message first.
server
socket.emit("news", {"hello": "hello"});
socket.on("news1", function(data){
console.log( "new " + data);
io.sockets.emit("news2", data);
});
client
socket.on('news', function(data){
console.log("data : " + data);
socket.emit("news1", {docker: "This is docker"});
});
socket.on('news2', function(data){
console.log("data : " + data);
});
Related
I am loading my scripts using
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="/js/chat.js"></script>
My chat.js script is :
var socket = io();
socket.on('connect', function(){
var chatForm = document.forms.chatForm;
if (chatForm) {
var chatUsername = document.querySelector('#chat-username');
var chatMessage = document.querySelector('#chat-message');
chatForm.addEventListener("submit", function(e){
console.log("working")
//prevents page from reloading
e.preventDefault();
//emit the message with the socket
socket.emit('postMessage',{
username: chatUsername.value,
message: chatMessage.value,
});
chatMessage.value='';
chatMessage.focus();
});//chatform event
socket.on('updateMessages', function(data) {
showMessage(data);
});//update messages
}//chatForm
})
function showMessage(data) {
var chatDisplay = document.querySelector('.chat-display')
var newMessage = document.createElement('p');
newMessage.className = 'bg-success chat-text';
newMessage.innerHTML = '<strong>' + data.username + '<strong>:</strong>' +
data.message
chatDisplay.insertBefore(newMessage, chatDisplay.firstChild);
}
My app.js file uses:
app.set('port', process.env.PORT || 3000 );
var server = app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
io.attach(server);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
I am getting the following errors in my console and have no idea how to fix them. Somebody please help!
The server is listening on port 3000. My console is saying that there is an unhandled 'error' event
In your app.js file, you should connect socketIO before listening:
const socketIO = require('socket-io');
const io = socketIO(app);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
app.set('port', process.env.PORT || 3000 );
app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
Let try it, because I think after listening, everything won't work. We should connect socketIO before listening.
I start create server with Nodejs and socket.io in simple way.
In client connect just fine but when emit pong to server it never show.
This code:
SERVER
var PORT = 3003;
var io = require('socket.io')(PORT);
var clients = [];
setInterval (function() {
io.sockets.emit('ping');
}, 3000);
io.on('connection', (function(socket) {
socket.emit ('welcome', { message: 'Connection complete', id: socket.id });
clients.push ({id: socket.id, clientSocket: socket});
print ('Client connected ' + socket.id);
socket.on('disconnect', function() {
clients.splice(clients.indexOf(socket), 1);
print (socket.id + " is disconnected.");
});
socket.on('pong', function(args) {
print (args + " is pong.");
});
}).bind(this));
print('Server starting ...');
CLIENT:
var PORT = 3003;
var io = require('socket.io-client');
var socket = io.connect('http://localhost:' + PORT);
socket.on('connect', function(){
print ('Client connected...');
});
socket.on('welcome', function(args) {
print (args.message + ' / ' + args.id);
// socket.disconnect();
});
socket.on ('ping', function(args) {
socket.emit ('pong', { id: socket.id });
print ('Receive ping...');
});
print ('Client Starting...');
i am developing simple chat application and i want to store messages in mongoDb.
but i am getting error when i run this code.
can not read property '_id 'of undefined. i already create one collection call chat.
var MongoClient= require('mongodb').MongoClient;
var assert=require('assert');
var ObjectId= require('mongodb').ObjectId;
var bodyParser= require('body-parser');
var express = require('express'),
app=express();
server=require('http').createServer(app),
io= require('socket.io').listen(server),
app.use(bodyParser.urlencoded({extended:false}));
var mongo=require('mongodb');
users = {};
url='mongodb://localhost:27017/anant';
server.listen(9000, function(){
var host= server.address().address;
var port=server.address().port;
console.log("save app listen on http://%s:%s", host , port);
});
/*var server = app.listen(9000, function(){
var host= server.address().address;
var port=server.address().port;
console.log("save app listen on http://%s:%s", host , port);
});*/
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.on('new user', function(data , callback){
if(data in users){
callback(false);
}else{
callback(true);
socket.nickname= data;
users[socket.nickname]= socket;
updatenicknames();
}
});
io.sockets.on('send request', function(data , callback){
var name=data;
console.log(data);
});
socket.on('send message', function(data , callback){
var msg=data.trim();
if(msg.substr(0,3) === '/w '){
msg = msg.substr(3);
var ind = msg.indexOf(' ');
console.log(ind);
console.log("got it after ind ");
if(ind !== -1)
{
var name=msg.substr(0, ind);
var msg=msg.substring(ind + 1);
console.log(name);
console.log(msg);
if(name in users){
console.log("got it in if name condition");
users[name].emit('wishper', {msg: msg , nick: socket.nickname} );
console.log('whisper..! ');
} else
{
callback("enter a vlid user");
}
} else{
callback('please enter message for your wishper');
}
}else {
insertData(data);
io.sockets.emit('new message', {msg: msg , nick: socket.nickname} );
}
});
function updatenicknames(){
io.sockets.emit('usernames', Object.keys(users));
}
function insertData(data)
{
MongoClient.connect(url, function(err, db){
console.log(data);
db.collection('chat').save(data.msg , (err,result)=>{
if(err){
console.log("not inserted");
}else {
console.log("inserted");
}
});
});
}
socket.on('disconnect', function(data){
if(!socket.nickname) return;
delete users[socket.nickname];
updatenicknames();
});
});
It's because you are passing a string data, to your insertData function (judging by your code, I guess you are supposing that data is actually an object).
Then you are giving data.msg, which is obviously undefined, as the first argument of the save methods, which is expecting you to provide a valid object here.
Please also note that you are using the save method on a newly created document, instead of using insertOne.
As you can see in the api documentation, using save is now deprecated. (I guess you are using the last version which is currently 2.1)
I want to send message to users if some new person is joining or user is quiting the chat.
i don't really know where to start to get this function work.
On disconnect message 'This users is gone' to all On Connect "user is connected to the chatbox"
app.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
nicknames = [];
server.listen(8000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.on('new user', function(data, callback){
if (nicknames.indexOf(data) != -1){
callback(false);
} else{
callback(true);
socket.nickname = data;
nicknames.push(socket.nickname);
updateNicknames();
}
});
function updateNicknames(){
io.sockets.emit('usernames', nicknames);
}
socket.on('send message', function(data){
io.sockets.emit('new message', {msg: data, nick: socket.nickname});
});
socket.on('disconnect', function(data){
if(!socket.nickname) return;
nicknames.splice(nicknames.indexOf(socket.nickname), 1);
updateNicknames();
});
})
;
You can use the broadcast function. This will broadcast to every other socket except the one that send the broadcast.
socket.on('disconnect', function () {
socket.broadcast.emit('leave',{name:name});
});
socket.on('leave', function (msg) {
//Add msg that msg.name is leaving
});
I'm working on a simple Node.js bi-directional client\server communication channel and I'm attempting to use socket.io on the server and socket.io-client on the client.
I've inserted the code below, as you'll see it's pretty basic stuff, and I'm running both on my local machine - to minimise complexity.
The behaviour I'm seeing is:
I start the server.
The server logs 'Server started' to the console.
I start the client.
The client logs 'Server is ready!'
Nothing else happens...
What I'd expect is the server to log a 'Client is ready!' message and then the content ('Ready received').
I've even used WireShark to sniff the line and it does appear that the client is emitting the message, as designed - but the callback on the server isn't firing.
I'm running node v0.8.4 with express v3.1.0, socket.io v0.9.13 and socket.io-client v0.9.11 (all installed via npm).
Here's the server code...
var http = require('http'),
express = require('express'),
app = express(),
server = http.createServer(app);
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
server.listen(8080);
console.log("Server started");
var io = require('socket.io').listen(server);
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
And here's the client code...
var clientio = require('socket.io-client');
var socket = new clientio.connect('http://localhost', { port: 8080 });
socket
.on('server ready', function(data){
console.log('Server is ready!');
socket.emit('comms', 'Ready received');
})
.on('connect-error', function(error) {
console.log('Connection Error\n' + error);
})
.on('error', function(error) {
console.log('Socket Error\n' + error);
})
The documentation and examples for both socket.io and socket.io-client are somewhat confused (to be charitable) and they appear to be a bit of a moving target... but from what I can tell, I think this should work.
I'm hoping someone can give me advice as to where I'm going wrong?
In your server you have this code:
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
What you should do is something like this:
io.sockets.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' });
socket.on('comm', function(content){
console.log('Client is ready!');
console.log(content);
});
});
hopefully this is doing more or less what you need it to do. Just a couple of minor changes.
app.js
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
// using 'connect' to handle static pages
app.use(require('connect').static(__dirname + '/public'))
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('server ready', { msg: 'ready' });
socket.on('comms', function(content) {
console.log(('Client is ready\n'));
console.log(content);
});
});
index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
window.jQuery || document.write('<script src="js/jquery-1.8.3.min.js"><\/script>')
</script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
(function (d, b) {
function bindEvents() {
function doSomething(msg) {
$.each(msg, function (key, value) {
console.log('doSomething...');
$("body").append("<p>" + value + "</p>")
});
};
// var socket = io.connect();
var socket = io.connect('http://localhost');
socket.on('server ready', function (msg) {
console.log('Server is ready!\n', msg);
doSomething(msg);
socket.emit('comms', {
msg: 'Client is Ready'
});
});
socket.on('connect-error', function (err) {
console.log('Connection Error\n', err);
});
socket.on('error', function (err) {
console.log('Connection Error\n', err);
});
};
$(document).ready(function () {
bindEvents()
});
})(jQuery, this)
</script>