Is it possible to use socket.io server with pure html5 websockets? - websocket

I want to use sockets in my web app. I don't want to use socket.io library on client-side. It's OK for server-side though. Can I do this?
Now with socket.io on server and pure websocket on client I have destroying non-socket.io upgrade error. I've googled that it means that I have to use socket.io-client library on client-side. Is there any way to avoid that? I don't want client to be tight with this library and use pure html5 websocket instead.
If it's not possible what should I use for server to connect with pure html5 websockets?
If someone is curious here is my server code (coffeescript file)
# Require HTTP module (to start server) and Socket.IO
http = require 'http'
io = require 'socket.io'
# Start the server at port 8080
server = http.createServer (req, res) ->
# Send HTML headers and message
res.writeHead 200, { 'Content-Type': 'text/html' }
res.end "<h1>Hello from server!</h1>"
server.listen 8080
# Create a Socket.IO instance, passing it our server
socket = io.listen server
# Add a connect listener
socket.on 'connection', (client) ->
# Create periodical which ends a message to the client every 5 seconds
interval = setInterval ->
client.send "This is a message from the server! #{new Date().getTime()}"
, 5000
# Success! Now listen to messages to be received
client.on 'message', (event) ->
console.log 'Received message from client!', event
client.on 'disconnect', ->
clearInterval interval
console.log 'Server has disconnected'
And here is a client-side
<script>
// Create a socket instance
socket = new WebSocket('ws://myservername:8080');
// Open the socket
socket.onopen = function (event) {
console.log('Socket opened on client side', event);
// Listen for messages
socket.onmessage = function (event) {
console.log('Client received a message', event);
};
// Listen for socket closes
socket.onclose = function (event) {
console.log('Client notified socket has closed', event);
};
};
</script>

I've found this library, seems OK for my needs https://npmjs.org/package/ws

Related

how to listen for all active websockets messages in javascript

hey guys so i have this email provider called https://emailfake.com/channel6/ i want a script that will listen for all ws comming messages for already opened connections
const socket = new WebSocket('wss://emailfake.com');
// Listen for messages
socket.addEventListener('message', (event) => {
console.log('Message from server ', event.data);
});
note : a script that will work on console of devtools

Why is my Socket.IO server not responding to my Firecamp and C# clients?

I am trying to set up a very basic Socket.IO server and a .NET / Firecamp client to learn how to send events between the two.
My Javascript Socket.IO server is set up like this:
const
http = require("http"),
express = require("express"),
socketio = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const SERVER_PORT = 3000;
io.on("connection", () => {
console.log("Connected");
io.emit("foo", "123abc");
});
server.listen(SERVER_PORT);
I am able to connect with a simple Socket.IO Javascript file:
const
io = require("socket.io-client"),
ioClient = io.connect("http://localhost:3000");
ioClient.on('connect', () => {
console.log("connected");
});
When I try to connect with Firecamp or this C# library I never see a connection event fired.
I looked at the default options for the Socket.IO JS client and tried to reproduce them in Firecamp: https://socket.io/docs/v3/client-api/index.html
The most important ones seem to be the Path= /socket.io, ForceNew = True, and Transports = polling, websocket. I decided to remove the polling transport because I kept getting an XHR polling error, but the websocket also times out in both C# and Firecamp.
I have tried connecting to "http://localhost:3000" and just "http://localhost".
Here is a screenshot of my Firecamp settings
I am also seeing a similar issue with my C# program
Quobject.Collections.Immutable.ImmutableList<string> trans = Quobject.Collections.Immutable.ImmutableList.Create<string>("websocket");
IO.Options options = new IO.Options();
options.Port = 3000;
options.Agent = false;
options.Upgrade = false;
options.Transports = trans;
client = IO.Socket("http://localhost:3000", options);
client.On(Socket.EVENT_CONNECT, () =>
Console.WriteLine("Connected"));
client.On(Socket.EVENT_CONNECT_ERROR, (Data) => Console.WriteLine("Connect Error: " + Data));
client.On(Socket.EVENT_CONNECT_TIMEOUT, (Data) => Console.WriteLine("Connect TImeout Error: " + Data));
client.On(Socket.EVENT_ERROR, (Data) => Console.WriteLine("Error: " + Data));
client.Connect();
If I only use a websocket transport I timeout in both Firecamp and C#. If I enable polling I receive the below error:
Error: Quobject.EngineIoClientDotNet.Client.EngineIOException: xhr poll error ---> System.AggregateException: One or more errors occurred. ---> System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.HttpWebRequest.GetResponse()
at Quobject.EngineIoClientDotNet.Client.Transports.PollingXHR.XHRRequest.<Create>b__7_0()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at Quobject.EngineIoClientDotNet.Client.Transports.PollingXHR.XHRRequest.Create()
--- End of inner exception stack trace ---
What other configuration settings can I toggle to try to get my Firecamp or C# connection to show up in my JS Server? I am receiving an "XHR Poll error" from the polling transport, and a timeout from the websocket transport. Is there additional debugging info somewhere I can use to determine where my problem lies? I think if I can get the communication working in either Firecamp or C# I should be able to get it working in the other environment.
I am assuming you're using the SocketIO v3 client. Firecamp is only supporting SocketIO v2. But the good news is in just two days Firecamp is going to give support for SocketIO v3 in the new canary release. I'll keep you posted here.
edited on 7th Sep'21
Firecamp is now supporting SocketIO v2, v3, and v4.
As mentioned above, Firecamp isn't optimized yet for the new version of Socket.IO (v4).
so meanwhile you can choose to manually enable compatibility for Socket.IO v2 clients.
All you have to do is to add "allowEIO3: true" (without quotes) as a key:value pair to the option object and pass this object when you create the server.
this will allow you to communicate with the server via Firecamp.
source https://socket.io/docs/v4/server-api/#Server
below you'll find an example for a working socket.io server integrated with express server.
const app = require('express')();
const httpServer = require('http').createServer(app);
const options = {
allowEIO3: true,
};
const io = require('socket.io')(httpServer, options);
app.get('/', (req, res) => {
res.send('home endpoint');
});
io.on('connection', (socket) => {
socket.on('new-connection', (data) => {
console.log(socket.id, 'connected');
socket.broadcast.emit('test-event', { name: data.name });
});
// when the user disconnects.. perform this
socket.on('disconnect', () => {
console.log(`${socket.id} disconnected`);
});
});
const port = 3000;
httpServer.listen(port, () => {
console.log(`server running on port ${port}`);
});

Socket.emit() outside socket.on()

Do we always have to use socket.emit() inside a socket.on() like that:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}
I want to create on my client side a function which ask information to the server when I click on a button:
translateServer(parameter, control){
this.socket.emit('translate', [parameter,control]);
}
But it seems that it's not working, the server never receive this message.
Thank you !
The pattern you are using above is the recommended way of interacting with a socket (ie acquiring a socket instance when the 'connection' event fires, and then calling emit() from that socket instance, etc).
If I understand your client-side requirements correctly, you are wanting to send data to the server via web sockets - are you sure the socket that you have established a web socket connection between the client and server?
For instance, if you add the following to your client-side code, you should see a success message in your console:
const socket = io.connect('YOUR SERVER ADDRESS');
socket.on('connect', () => {
console.log('connected to server!');
// [UPDATE]
// This assumes you have a <button> element on your page. When
// clicked, a message will be sent to the server via sockets
document.querySelector('button').addEventListener('click', (event) => {
// Prevent button click reloading page
event.preventDefault();
// Send message to server via socket
socket.emit('MESSAGE_ID', 'test message from client' + new Date());
});
});
Update
This shows your original server code, expanded with the detail needed to receive and print data sent from client via sockets:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
// Register a server handler for any messages from client on MESSAGE_ID channel
socket.on('MESSAGE_ID', (message) => {
// Print the message received from client in console
console.log('message from client', message);
})
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}

socket.io connection event never fire

server
var io = require('socket.io'),
UUID = require('node-uuid'),
gameport = 3000;
var db = {
waiting_clients: []
};
var logic = {
};
var sio = io.listen(gameport);
sio.sockets.on('connection', function(socket){
var client = {
id: UUID()
};
socket.emit('news', client);
console.log(client.id);
db.waiting_clients.push(client);
});
test client:
var net = require('net');
var client = net.connect({port: 3000},
function(e) { //'connect' listener
console.log('client connected');
client.end();
});
in test client console, it show "client connected". But there are no output in server console
You must use a socket.io client to connect to a socket.io server. Your code shows that you are trying to make a generic TCP connection to a socket.io server. That will not work. The lowest level connection will be established, but then the initial protocol handshake will fail and the socket.io server will drop the connection and you will never get the connection event.
Socket.io has its own connection scheme built on top of webSocket which is built on top of HTTP which is built on top of TCP.
So, to connect to a socket.io server, you must use a socket.io client that runs both the socket.io and webSocket protocol, not a plain TCP socket.

socket.io emit all clients not emitting over SSL

I have the normal socket.io set up:
Client:
import io from 'socket.io-client'
const socket = io()
socket.on('connect', () => {
console.log('connected')
socket.emit('message', 'I have connected')
})
socket.on('message', (msg) => console.log(msg))
Server:
import socket from 'socket.io'
const io = socket(/* httpsServer */)
io.on('connection', (socket) => {
console.log('new connection')
socket.on('message', (msg) => console.log(msg))
socket.emit('message', 'This works!')
io.sockets.emit('message', `This doesn't!`)
})
For some reason emit to all works perfectly via http but not https. Via https the io.sockets.emit doesn't seem to work. Am I missing something?
Check the same socket server module isn't mounted to both httpServer and httpsServer.
I wrapped my socket server in a module and attached it first to the https server and then to the http server. This is why the single sockets would connect but then emit to all was trying to send out to the http sockets only.

Resources