c# SocketIoClientDotNet, node js socket.IO - socket.io

c# winform tries to send node.js socket through socket.
The client is connected to server, but the socket.emit value and socket.on value do not communicate normally.
I'd like to find a solution to this.
I would like to send this name of client to the server as json type data, receive json type data from the server, read it, and send data back to json.
The data of socket.emit and socket.on are not working properly, so the code has been deleted.
c# code
private void socketLogin(string email, string pw)
{
var socket = IO.Socket("http://localhost:3000/login.html");
socket.On(Socket.EVENT_CONNECT, () =>
{
});
var loginjson = new JObject();
loginjson.Add("email", email);
loginjson.Add("password", pw);
socket.Emit("socketlogin", loginjson.ToString());
socket.On("login", (data) => {
MessageBox.Show(data.ToString());
});
}
node.js Code
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
console.log('connection');
socket.on('socketlogin', function(data) {
var testLogin = { 'Login': "success" };
socket.emit('login', data);
});
});
server.listen(app.get('3000'))

in your C# you are making your socket inside a function, but at the end of the function the socket is thrown away because it is only a local variable.
There are many ways to deal with this, but essentially what you want to do is use a thread to handle the socket comms then dispatch things back to your UI thread.

Related

Socketio: How can i send a single string over to the client

I am trying to send a string to the client like this:
socket.emit("start", "calm");
but it is throwing an error, is it because it is not an object ?
First thing first, you should make sure your socket between server-side and client-side is connect. And register event and function to the socket.
Server-side
io.sockets.on('connection', function(socket) {
console.log('socket connect' + socket.id);
// when a client connect to server within socket, server will send hello
io.emit('newMsg', "hello")
socket.on('disconnect', function() {
console.log('socket disconnect');
})
// when server receive a message, it will send to all client which connect
to the server
socket.on('data', function (data) {
console.log(socket.id +': ' + data.msg);
var message = {from: socket.id,
msg: data.msg
}
io.emit('newMsg', message)
})
}
Client-side
var socket = io('http://localhost:3000');
socket.on('connect', function (data) {
console.log(data)
})
socket.on('newMsg', function(data) {
console.log(data)
})
// function could bind on button on client side page, get input and send data
function sendData() {
var input = document.getElementsByTagName('input')
var text = input[0].value
var data = { msg: text }
socket.emit('data', data)
}
open console, the information would show in the console. When sending a message on server-side, could use 'broadcast' instead of 'emit' as well to send the message to other clients except you. Read the doc: socket.io doc

Socket.IO client cannot send handshake parameter

Here is my code:
var socket = require('socket.io-client')('http://127.0.0.1:3000/printers', {
query: "shop=" + "123456",
transports: ["websocket"]
});
If I delete query, I can connect to socket. Where am I wrong?
There doesn't seem to be anything wrong with your client-side code. I can connect by copying and pasting your code.
I suspect the problem is within your server-side code. Here is an example I am using with your client-side code:
var http = require('http');
var io = require('socket.io');
var server = http.createServer(function(req,res){
res.writeHead(200);
res.end('Hello, World!\n');
});
server.listen(80);
var socket = io.listen(server);
socket.use(function(socket, next){
console.log("Query: ", socket.handshake.query);
if (socket.handshake.query.shop == '123456') {
next();
}
next(new Error('You cannot use that shop'));
});
socket.on('connection', function(client) {
console.log('New Connection');
});
I'm able to obtain the query data in the 'socket.use' function. If I don't call the next() function, the client will never get the message that the server has received the response and is connected.
I recommend checking out the example used in this thread.

socket.io data from server to client

server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/public'));
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
io.emit('messages', 'Hello');
});
});
index.html
<script>
var socket = io.connect('http://localhost:7777');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
socket.on('messages', function(data) {
alert(data);
});
</script>
I tried to implement very basic of Socket.io.
However, data sending from client to server is available but from server to client doesn't work.
In the command running server.js, 'Hello World from client' is printed. However, alert window doesn't work in the web browser.(I've also tried to console.log).
How to solve this?
Editted
I've put server.js codes in the app.get('/', function(req, res)){ ... }
Then, it doesn't work. Why it doesn't work in app.get?
Try this, I hope it works:
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
io.emit('join', data); //this code sending data from server to client
});
});
If you're just trying to fetch some data with an Ajax call such as /test, then there is no need to use socket.io. That's just a classic request/response.
app.get('/test', function(req, res) {
// collect your data and then send it as a response
res.json(data);
});
If you're just trying to incorporate data into a web page that is requested, then you can use res.render() with the template engine of your choice (ejs, handlebars, pug, etc...). That would typically look like this:
app.get('/test', function(req, res) {
// collect your data and then pass it to res.render() to render your
// your template using that data
res.render('someTemplateName', data);
});
The main thing that socket.io is useful for is "pushing" data from server to client without a client request. So, if something happened on the server that the client was not aware of and the server wanted to tell the client about it, then socket.io would be used for that. The classic example is a chat app. Person A sends a chat message to the server that is addressed to Person B. The server receives that message and then needs to "push" it to Person B. That would be perfect for an already connected socket.io connection because the server can just push the data directly to the Person B client, something the server can't do with request/response (since there is no request from person B).
If you still think you need socket.io, then please describe exactly what you're trying to do with it (step by step what you're trying to send to the client).
socket.on("message",function (reply_data) {
console.log('inside on message functions ')
console.log(reply_data);
})
please change 'messages' to "message" that worked for me

what does the socket parameter mean in the callback in socket.io/websocket?

In socket.io example code we have something like this: (probably similar in other websocket framework/libraries)
io.on('connection', function (socket) {
io.emit('this', { will: 'be received by everyone'});
socket.on('private message', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
});
socket.on('disconnect', function () {
io.emit('user disconnected');
});
});
But I am not sure what this socket stands for. Is it the latest connected socket?
UPDATED:
Suppose I have used a list to store sockets with different id:
let list = {};
Then
import socketActions from './socketactions';
io.on('connection', function(socket) {
return socketActions(socket, list);
}
in socketactions.js:
function socketActions(socket, list) {
socket.id = Math.random();
list[socket.id] = socket;
socket.on('init', function(data) {
// process data
}
socket.on('sendMsg', function(data) {
// process data
}
}
export {socketAction};
Because the IDs are different the sockets in the list will be different, meaning different user connections. Now somewhere in my server I want to broadcast to other users in the network:
for (const i in list) {
const socket = list[i];
socket.broadcast.emit('timeToDoSomething', handler);
}
Now what is the difference between the socket in the list and the socket I used in the io.on('connection', function(socket) {});?
Now what is the difference between the socket in the list and the
socket I used in the io.on('connection', function(socket) {});?
There is no difference, they contain the same socket objects. Your code:
list[socket.id] = socket;
just saved the socket object into your own data structure so you could later reference it via your list data structure.
Note - you don't have to make your own map of the sockets like this. socket.io keeps one for you already. Instead, you can just access:
io.sockets.connected
at any time. It is a map with the id as the key and the socket as the value.
// given an id, get a socket
let socket = io.sockets.connected[someSocketId];
// send a message to just that socket
socket.emit("hello");
In addition, if you want to send a message to all connected sockets, you can just use:
io.emit('timeToDoSomething', data);
This will automatically iterate through all the connected sockets and send each one the same message.

Node app; Call server function from Client

I can't seem to call a server function from my client using either socket.io or an ajax call. Any help would be appreciated. For socket.io, I was trying something like this:
server (no error is being thrown, only I never see the console.log):
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var socket = io.sockets.on('connection', function(socket) {});
socket.on('admin-refresh', function() {
console.log("*** Admin refresh ***");
});
client (yes I'm including all necessary files, no error is being thrown on client side nor server):
$('document').ready(function() {
var socket = io();
$('#refresh').click(function() {
console.log('refresh clicked..');
io.emit('admin-refresh');
});
});
I don't need any data to be passed, I just want to alert the server to call a function. So perhaps an ajax call would be easier? How would I set up the server to listen for calls?
Why do you have an empty connection callback..? Look at the docs again.
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('admin-refresh', function() {
console.log("*** Admin refresh ***");
});
});

Resources