I have a working socket.io server up and running, and i am trying to implement a server side socket.io client. Below is the code snippet i have been using for testing. The problem with this is that the client outputs the message only once, in this case it receives 'Welcome' only. I have tried sending messages to the private channel, 'message' via browser but it doesn't show any output even though the server can receive and emit the message successfully.
Client
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {'force new connection': true});
socket.on('connect', function(){
socket.on('message', function (data) {
console.log(data);
});
});
Server
var io = require('socket.io').listen(server);
var i=0;
io.sockets.on('connection', function (socket) {
socket.emit('message', { 'msg': 'Welcome'});
socket.on('message', function (from, msg) {
socket.emit('message', { 'msg': 'Hello World - ' + i });
i++;
});
});
Have you tried doing this?
console.log(data.msg);
Can you try changing "socket" to "this":
this.emit('message', { 'msg': 'Hello World - ' + i });
You should emit from client side to server. So server can send the data back to client. I guess this code works fine :-)
Client
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {'force new connection': true});
socket.on('connect', function(){
socket.on('messageRecieved', function (data) {
console.log(data);
});
socket.emit('message','some message');
});
Server
var io = require('socket.io').listen(server);
var i=0;
io.sockets.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log(msg);
socket.emit('messageRecieved', { 'msg': 'Hello World - ' + i });
i++;
});
});
Related
Okay as I said i the title when I go to my home page the socket connection works perfectly but when I use a route it doesnt work at all here is my index.js
io.of('/admin').on('connection', function(socket) {
console.log('made socket connection', socket.id);
console.log(socket.request.user);
socket.on('chat', async function(data) {
console.log(data);
client.guilds.channels.get('474951005788962846').send(data);
io.sockets.emit('chat', data);
});
});
io.on('connection', function(socket) {
console.log('made socket connection', socket.id);
console.log(socket.request.user);
socket.on('chat', async function(data) {
console.log(data);
client.guilds.channels.get('474951005788962846').send(data);
io.sockets.emit('chat', data);
});
});
and on my /admin page here is my script that it is the same but the connection isnt as I added the /admin
<script>
var socket = io.connect('https://domain/admin');
// Query DOM
var serverID = document.getElementById('add_server_id');
var serverRoles = document.getElementById('add_role_ids');
var btnServer = document.getElementById('add_server_save');
//var output = document.getElementById('output');
// Emit events
btnServer.addEventListener('click', function(){
socket.emit('chat', {
serverid: serverID.value,
serverroles: serverRoles.value
});
});
//Listen for events
socket.on('chat', function(data) {
console.log(data);
//output.innerHTML += '<p><strong>' + data.game + '</strong></p>';
});
</script>
if someone can tell me why is it not connecting I would really appreciate it
var socket = io.connect('https://domain/admin');
to
var socket = io.connect('/admin');
The namespace is an implementation detail of the Socket.IO protocol,
and is not related to the actual URL of the underlying transport,
which defaults to /socket.io/….
Node js net module server code:
var net = require('net');
var server = net.createServer(function (connection) {
console.log('client connected');
connection.on('data', function (data) {
console.log('data from flash = ' + data);
var jsonData = {};
jsonData.message = "joined";
var d = JSON.stringify(jsonData);
connection.write(d);
});
connection.on('end', function () {
console.log('client disconnected');
});
// connection.pipe(connection);
});
server.listen(3055, function () {
console.log('server is listening');
});
Action script code
this.login_socket.connect(this.server_ip,3055);
this.login_socket.addEventListener(Event.CONNECT,this.login_socket_onConnection);
this.login_socket.addEventListener(DataEvent.DATA,this.login_onData);
this.login_socket.addEventListener(IOErrorEvent.IO_ERROR,this.login_socket_onIOErrorEvent);
this.login_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,this.login_socket_SecurityErrorEvent);
this.login_socket.addEventListener(Event.CLOSE,this.login_socket_closeErrorEvent);
Can anyone please tell me how to use xml socket with node js net module? I have tried everything but this doesn't work at all. I want to create a socket connection for a flash game to the server. I am using laravel as backend. If anyone knows how to create it with php tell me. Thank you.
var net = require('net');
var server = net.createServer(function (connection) {
console.log('client connected');
connection.setEncoding("utf8");
// on receive data from client
connection.on('data', function (data) {
console.log('data from flash = ' + data);
var d = JSON.stringify({
message: "joined"
}) + "\0";
connection.write(d);
});
// on connection end
connection.on('end', function () {
console.log('client disconnected');
});
// on error
connection.on("error", function (exception) {
console.log('an error occurred: ' + exception);
});
});
server.listen(3055, function () {
console.log('server is listening');
});
I change nodejs server code to above code and it works fine now.
I am having trouble sending "hi" message from the client to the server. There socket is connected and I am receiving a message when the connection is established on the client. But when I try to emit a message back to the server, it doesn't work.
I have tried both Android and HTML. So I am pretty sure its the server.
NODE
var socket = require('socket.io');
var io;
module.exports = {
initialize: function(server) {
io = socket.listen(server);
io.on('connection', function(socket) {
socket.emit('message');
console.log('connected to socket');
});
io.on('hi', function(message) {
console.log(message);
});
}
}
HTML
doctype html
html
head
title Example
script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')
script(src='/socket.io/socket.io.js')
script(type"text/javascript").
var socket = io.connect('http://localhost:3000')
socket.on('message', function(data){
console.log('receive message from server on webpage');
});
body
div.container
header
h1 Socket Test
button#hiButton Send Hi
footer
script(type"text/javascript").
$('#hiButton').click(function(){
socket.emit('hi', 'send hi to server from webpage');
});
Found the answer
var socket = require('socket.io');
var io;
module.exports = {
initialize: function(server) {
io = socket.listen(server);
io.sockets.on('connection', function(socket) {
socket.emit('message');
socket.on('hi', function(message) {
console.log(message);
});
console.log('connected to socket');
});
}
}
I have a socket.io server running and a matching webpage with a socket.io.js client. All works fine.
But, I am wondering if it is possible, on another machine, to run a separate node.js application which would act as a client and connect to the mentioned socket.io server?
That should be possible using Socket.IO-client: https://github.com/LearnBoost/socket.io-client
Adding in example for solution given earlier. By using socket.io-client https://github.com/socketio/socket.io-client
Client Side:
//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {reconnect: true});
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');
Server Side :
//server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function (socket){
console.log('connection');
socket.on('CH01', function (from, msg) {
console.log('MSG', from, ' saying ', msg);
});
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
Run :
Open 2 console and run node server.js and node client.js
After installing socket.io-client:
npm install socket.io-client
This is how the client code looks like:
var io = require('socket.io-client'),
socket = io.connect('http://localhost', {
port: 1337,
reconnect: true
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });
Thanks alessioalex.
const io = require('socket.io-client');
const socket_url = "http://localhost:8081";
let socket = io.connect(socket_url);
socket.on('connect', function () {
socket.emit("event_name", {});
});
Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.
Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!
const socket = require('socket.io-client')('http://192.168.0.8:5000', {
reconnection: true,
reconnectionDelay: 10000
});
socket.on('connect', (data) => {
console.log('Connected to Socket');
});
socket.on('event_name', (data) => {
console.log("-----------------received event data from the socket io server");
});
//either 'io server disconnect' or 'io client disconnect'
socket.on('disconnect', (reason) => {
console.log("client disconnected");
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
console.log("server disconnected the client, trying to reconnect");
socket.connect();
}else{
console.log("trying to reconnect again with server");
}
// else the socket will automatically try to reconnect
});
socket.on('error', (error) => {
console.log(error);
});
something like this worked for me
const WebSocket = require('ws');
const ccStreamer = new WebSocket('wss://somthing.com');
ccStreamer.on('open', function open() {
var subRequest = {
"action": "SubAdd",
"subs": [""]
};
ccStreamer.send(JSON.stringify(subRequest));
});
ccStreamer.on('message', function incoming(data) {
console.log(data);
});
I am using socket.io in nodejs and I am able to send data from client to server. But when I emit from server, the client does not seem to be receiving this...
What am i missing ?
server:
socket = io.listen(app);
socket.sockets.on('connection', function(client){
client.on('something-from-client', function(msg){
console.log(msg);
//do something.
client.emit('some-result',{"total":docs.length});
});
});
client:
var socket = io.connect('http://localhost:9999');
socket.on('some-result', function(data){
console.log('received from server', data);
});
socket.emit("something-from-client", {"lat":lat, "lng":lng});
Ok got it working, if express is being used, some minor changes need to be done on server side
var port = 8111;
var server = express.createServer();
io = require('socket.io').listen(server);
server.listen(port);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
As promised - Working code - https://github.com/parj/node-websocket-demo/tree/socket_emit
CF Reference - http://socket.io/#how-to-use