When one user adds an event using API, other users should get an alert about new event
Is it possible to:
send message from client-side when one user adds an event using wss://echo.websocket.org
let socket = new WebSocket('wss://echo.websocket.org');
socket.onopen = () => socket.send('New event');
and get this message from other browser?
let socket = new WebSocket('wss://echo.websocket.org');
socket.onmessage = function(event) {
var message = event.data;
alert(message)
};
server-side on PHP
Is there any source based on "How to realize WebSocket server ( PHP )"?
I don't want to send request to server every some inetrval for checking updates, is there any wat to keep connection alive and when got response show alert to the client?
Related
I have an application and I would like prevent message handling from another tab.
//client
var msg_chan = new MessageChannel();
// Handler for recieving message reply from service worker
msg_chan.port1.onmessage = function(event){
if(event.data.error){
reject(event.data.error);
}else{
resolve(event.data);
}
};
const id = (new Date().getTime() / 1000).toFixed()
// Send message to service worker along with port for reply
navigator.serviceWorker.controller.postMessage({ message, id }, [msg_chan.port2]);
In this way, if multiple tabs are opened service worker handles the message in both tabs.
// service-worker.js
self.addEventListener('message', event => {
console.log(event.data) // This prints two times if two tabs are open
})
Is it possible to handle message for once?
You can assign each tab a clientId and send it on the messages.
I'm a starter developer. I use socket.io for my app, which is based on a chat app.
I have a problem when the client disconnects accidentally (E.g. wi-fi on the PC disconnects). When wi-fi is connected again, the client enters the 'reconnect' event. After that, the connection is correctly reseted in the upper way (client to server) but won't work in the down way (server to client). After the re-connect my client will emit events that run on the server... but the server can't emit events that work on the client (the one that reconnected).
E.G:
client side:
I have this button created when the user logs in that when clicked sends the 'ready' event to the server.
socket.on('login', function (data) {
connected = true;
$matchId=data.id
var btn;
btn = document.createElement("BUTTON");
btn.innerHTML= "Ready";
btn.className = "readybtn";
btn.id = "readyBtn";
btn.onclick = function ready(){
socket.emit('ready',{
id: $matchId
});
};
document.getElementById("dropdownDiv").appendChild(btn);
});
server side (extract of one of the multiple events i've designed).
io.on('connection', function (socket) {
socket.on('ready', function(data){
var matchIdx;
for (var i = 0; i < srv.matches.length; i++) {
if(srv.matches[i].matchId == data.id) matchIdx = i;//indexOf
}
socket.to(srv.matches[matchIdx].matchId).emit('new message',{
username:socket.username,
message: "I'm ready"
});
}
});
Therefore, as you can see the when some client clicks on the Ready button, a I'm ready message with the client's username appears to everybody in the room.
My problem comes here, after the reconnect event (from socket.io) if I test this, the message will be displayed on all the clients except for those that reconnected. Even if I switch off the wi-fi on a client and then click on the ready button, I will see the I'm Ready message in all the clients but the one that reconnected. This means, that after the reconnect, the client is able to trigger the 'ready' event of the server, but the server cannot establish the connection to the client, since the 'new message' event is not triggered in the reconnected client.
I've tried to emit directly to the client that reconnected, to check if it is related to the rooms, but it does not work either.
Can somebody tell me how to solve this? Refreshing is not an option..
Thanks in advance.
I attach the reconnect event:
socket.on('reconnect', function () {
log("you were reconnected");
});
PS: Sorry for poor English and explanation, it is my first question.
My problem is that the current solution I have for sending a specific socket using the library "ws" with node.js is not good enough.
The reason is because if I connect with multiple tabs to the websocket server with the same userid which is defined on the client-side, it will only refer to the latest connection with the userid specified.
This is my code:
// Server libraries and configuration
var server = require("ws").Server;
var s = new server({ port: 5001});
// An array which I keep all websockets clients
var search = {};
s.on("connection", function(ws, req) {
ws.on("message", function(message){
// Here the server process the user information given from the client
message = JSON.parse(message);
if(message.type == "userinfo"){
ws.personName = message.data;
ws.id = message.id;
// Defining variable pointing to the unique socket
search[ws.id] = ws;
return;
}
})
})
As you can see, each time a socket with same id connects, it will refer to the latest one.
Example If you did not understand:
Client connect to server with ID: 1337
search[1337] defined as --> websocket 1
A new connection with same ID: 1337
search[1337] becomes instead a variable refering to websocket 2 instead
Websockets provide a means to create a low-latency network "socket" between a browser and a server.
Note that the client here is the browser, not a tab on a browser.
If you need to manage multiple user sessions between the browser and server, you'll need to write code to do it yourself.
I am trying to create a system where I have a desktop client created in VB, and a browser based client, that can send messages to each other. I am using a Node.js server to handle the connections and messages.
This is the code of my Node.js server:
net = require('net')
// Supports multiple client chat application
// Keep a pool of sockets ready for everyone
// Avoid dead sockets by responding to the 'end' event
var sockets = [];
// Create a TCP socket listener
var s = net.Server(function (socket) {
// Add the new client socket connection to the array of
// sockets
sockets.push(socket);
// 'data' is an event that means that a message was just sent by the
// client application
socket.on('data', function (msg_sent) {
// Loop through all of our sockets and send the data
for (var i = 0; i < sockets.length; i++) {
// Don't send the data back to the original sender
if (sockets[i] == socket) // don't send the message to yourself
continue;
// Write the msg sent by chat client
sockets[i].write(msg_sent);
}
});
// Use splice to get rid of the socket that is ending.
// The 'end' event means tcp client has disconnected.
socket.on('end', function () {
var i = sockets.indexOf(socket);
sockets.splice(i, 1);
});
});
s.listen(8000);
console.log('System waiting at http://localhost:8000');
With this sever, I am able to send messages between two desktop clients successfully.
However, because I am using net and not HTTP I cannot get the browser based client to connect.
How can I get both the clients to connect? I would really appreciate any help/suggestions/directions. I have been searching everywhere for about 4 days now! TIA!
You could use http or express for browser based client. could check socket.io also which works on http port.
I would try to help more if know type of the desktop client you are using.
I am trying to proxy emails via NodeJS in order to do very custom processing on outgoing emails on our test server.
This is what I have:
var net = require('net');
var server = net.createServer({allowHalfOpen: true}, function(socket) {
console.log('New connection established.');
socket.setEncoding('utf8');
socket.on('data', function(data) {
console.log(data);
});
socket.on('end', function() {
console.log('Connection closing.');
});
socket.resume();
});
server.listen(25);
It does not yet process the emails, because it simply doesn't even work. I get the connection established message in console every time I send an email, but the data event never gets fired. I'm not sure if it's that the data already came before I bound the event listener, or whether I'm supposed to talk to the client first (HELO?).
I'm trying to access the email contents, basically.