On my server I call two emits at the same time, which looks like this.
if (songs.length > 0) {
socket.emit('data loaded', songs);
socket.broadcast.to(opponent).emit('data loaded', songs);
}
The one is for opponent and the other for himself.
Once the data is loaded a countdown should appear for both players on my android app. For me it is important that they see the same number at the same time on their screen. To be precise it should run synchronized. How can I do this?
Or using an existing protocol, like STOMP or similar. Socket IO’s initial attraction was that you could build a chat service which didn’t require continually polling the server for new messages, and anything you types could appear on multiple clients seemingly immediately.
A much better approach can be to use socket.io rooms to maintain the individual connections for a user. For every socket connection the user makes, we add the socket instance to a room dedicated for this user. Let's call the room, "Room:Josh".
You write to one socket, and it appears byte for byte on the other socket’s read buffer. When you make an HTTP request over the internet, it typically opens a socket connection to the server, and sends a request header, followed by an optional request body.
Low level sockets are essentially a stream of bytes. You write to one socket, and it appears byte for byte on the other socket’s read buffer. When you make an HTTP request over the internet, it typically opens a socket connection to the server, and sends a request header, followed by an optional request body.
As far as js timers are concerned the will be a small amount of difference. We can reduce the difference in time with reduce of latency time, with the difference between the request and response time from the server.
function syncTime() {
console.log("syncing time")
var currentTime = (new Date).getTime();
res.open('HEAD', document.location, false);
res.onreadystatechange = function()
{
var latency = (new Date).getTime() - currentTime;
var timestring = res.getResponseHeader("DATE");
systemtime = new Date(timestring);
systemtime.setMilliseconds(systemtime.getMilliseconds() + (latency / 2))
};
res.send(null);
}
Elapsed time between sending the request and getting back the response need to be calculated, divide that value by 2. That gives you a rough value of latency. If you add that to the time value from the server, you'll be closer to the true server time (The difference will be in microseconds)
Reference: http://ejohn.org/blog/accuracy-of-javascript-time/
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With