/r/websocket
News and links to new Websocket developments.
/r/websocket
import os
from channels.routing import ProtocolTypeRouter , URLRouter
from channels.auth import AuthMiddlewareStack
from tictac.consumers import GameRoom
from django.core.asgi import get_asgi_application
from django.urls import path
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TICTACTOE.settings')
application = get_asgi_application()
ws_pattern =[
path('ws/game/<code>', GameRoom)
]
application= ProtocolTypeRouter(
{
'websocket':AuthMiddlewareStack(URLRouter(
ws_pattern
))
}
)
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
import json
class GameRoom(WebsocketConsumer):
def connect(self):
self.room_name = self.scope['url_route']['kwargs']['code']
self.room_group_name = 'room_%s' % self.room_name
print(self.room_group_name)
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
def receive(self , text_data):
print(text_data)
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,{
'type' : 'run_game',
'payload' : text_data
}
)
def run_game(self , event):
data = event['payload']
data = json.loads(data)
self.send(text_data= json.dumps({
'payload' : data['data']
}))
<script>
var room_code = '{{room_code}}'
var name = '{{name}}'
var player = name.charAt(0)
let socket = new WebSocket('ws://localhost:8000/ws/game/' +room_code)
let gameState = ["","","","","","","","",""]
let elementArray = document.querySelectorAll('.space')
elementArray.forEach(function(elem){
elem.addEventListener("click" , function (event){
setText(event.path[0].getAttribute('data-cell-index') , player)
})
})
function checkGameEnd(){
var count = 0;
gameState.map((game)=>{
if(game != ""){
count++;
}
})
if(count >= 9){
var data = {'type' : 'over'}
socket.send(JSON.stringify({data}))
swal("Good over!" , "Game end no one won" , "warning")
}
}
function checkWon(value , player){
var won = false;
if(gameState[0] === value && gameState[1] == value && gameState[2] == value){
won = true;
}else if(gameState[3] === value && gameState[4] == value && gameState[5] == value){
won = true
}else if(gameState[6] === value && gameState[7] == value && gameState[8] == value){
won = true
}
else if(gameState[0] === value && gameState[3] == value && gameState[6] == value){
won = true
}
else if(gameState[1] === value && gameState[4] == value && gameState[7] == value){
won = true
}else if(gameState[2] === value && gameState[5] == value && gameState[8] == value){
won = true
}
else if(gameState[0] === value && gameState[4] == value && gameState[8] == value){
won = true
}
else if(gameState[2] === value && gameState[4] == value && gameState[6] == value){
won = true
}
if(won){
var data = {'type' : 'end' , 'player' : player}
socket.send(JSON.stringify({data}))
swal("Good job!" , "You won" , "success")
}
checkGameEnd();
}
function setText(index , value){
var data = {
'player' : player,
'index' : index,
'type' : 'running'
}
if(gameState[parseInt(index)] == ""){
gameState[parseInt(index)] = value
elementArray[parseInt(index)].innerHTML = value
socket.send(JSON.stringify({
data
}))
checkWon(value , player )
}else{
alert("You cannot fill this space")
}
}
function setAnotherUserText(index , value){
gameState[parseInt(index)] = value
elementArray[parseInt(index)].innerHTML = value
}
socket.onopen = function (e){
console.log('Socket connected')
}
socket.onmessage = function (e){
var data = JSON.parse(e.data)
console.log(data)
if(data.payload.type == 'end' && data.payload.player !== player){
swal("Sorry!" , "You lost" , "error")
}else if(data.payload.type == 'over'){
swal("Game over!" , "Game end no one won" , "warning")
return;
}else if(data.payload.type == 'running' && data.payload.player !== player){
setAnotherUserText(data.payload.index , data.payload.player)
}
}
socket.onclose = function (e){
console.log('Socket closed')
}
</script>
Hi all, I am currently searching (as the title says) for a websocket server that is compatible with the pusher protocol (i.e. works with laravel echo).
We are currently using soketi, but since they are incredibly slow to add support for Node > 18 (i.e. any never Node version that actually has support left) we need alternatives. This dependency on an old node version is holding us back on updating node in other projects since it breaks some dev environments.
Now, to my surprise, I have not found a suitable alternative yet!
Obviously the big (paid and proprietary) players, but nothing one could easily self host for free.
(I know, laravel reverb exists, but that is just too much... The simplicity of just starting up socketi on a specific port with some keys in the .env is just too good. Something like that with 0 extra configuration to make the service actually run would be the dream.)
There aren't any real constraints apart from compatibility with laravel echo.
It should be easy to launch on a dev machine as well as easy to build into a docker image (or maybe even ship with one?).
Any language is welcome, support for WSS would be nice, but not needed.
Oh, and a recent toolchain and relatively active development so we don't corner ourselves again like with soketi would be awesome...
Maybe someone has an idea, because I can't imagine there to be no tool like this in an awesome FOSS world where everyone needs websockets nowadays...
Hey Guys,
I have an application which has large dataset that is streamed through websockets currently and visible in a ag-grid table and there are various realtime updates that keep on flowing to browser through socket related to that data.
Since the data is huge and updates are also becoming very large, I want to control the data in table through pagination and send updates for only the specific data that is in the view...Updates are currently asynchronous that my backend receives through third party system and backend sends all updates to UI.
Wanted to get the insights how can I implement this change to my system and make it robust.
Hello, I', trying to implement private notifications using soketi, the public channels work perfectly because it uses ws port, but when the site is secured or the channel is private, it uses wss, which shows this error:
WebSocket connection to 'wss://127.0.0.1:6001/app/app-key?protocol=7&client=js&version=8.4.0-rc2&flash=false' failed: An SSL error has occurred and a secure connection to the server cannot be made.
I did not find anyway or any tutorials on making wss available on valet. do you have any suggestions regarding that? I'll provide any needed resources..
Hi !
I want a Unity game communicate with an other Unity client.
Data Will be send every 10ms From client A to client B.
TCP Is The best option ? Or Websocket ? Is there stream on tcp/websocket ?
Which language best fit for performance ?
Other good option in mind ?
Thanks you !
Can anyone tell me how I can host my websocket (socket io ) hopefully without a card?
github.com/gorilla/websocket
As gorilla websocket has been archived which library can we use?
Hi Everyone!
Some of the posts on here are really great!
Im a noob here and in the field of what I'm trying to do too. I have started to create a multiplayer game but it was using short polling and I don't think that is going to be best long term.
After completing a basic POC I started to rebuild and decided to use websockets as a solution.
I'm running a virtual private Linux server from Ionos Plesk is installed I have created a subdirectory called server in httpdocs which is where the app.js file is for server creation. Port 8080 is open Im using http/ws for now before I attempt to go near https/wss I have enabled NodeJS on the server and set up the following as config:
Document Root: /httpdocs/server
Application URL: http://[my.url]
Application Root /httpdocs/server
Application Startup File app.js
The app.js contains:
var Msg = ''; var WebSocketServer = require('ws').Server , wss = new WebSocketServer({port: 8080}); wss.on('connection', function(ws) { ws.on('message', function(message) { console.log('Received from client: %s', message); ws.send('Server received from client: ' + message); }); });
On any web page that loads on that domain I now get an error stating 'Upgrade Required' error 426 I know that means the server wants the client to upgrade to websockets but I cant understand why the client isn't asking to upgrade back.. In my ws_test.html file I access to test the connection this is the code in the HTML body:
<script> let socket = new WebSocket("ws://[my.url]/server/app.js"); socket.onopen = function(e) { alert("[open] Connection established"); alert("Sending to server"); socket.send("TEST SUCCESSFUL"); }; </script>
I have tried so many different things and come to the end of my tether.. I have changed the connection URL many times and the ports. I suspect NGINX may have something to do with it but I tried disabling proxy and no change.
Can anyone see any glaringly obvoius mistakes!?
Thanks SO SO much for just reading this any help will be hugely appreciated.
I have tried so many different things and come to the end of my tether.. I have changed the connection URL many times and the ports. I suspect NGINX may have something to do with it but I tried disabling proxy and no change.
Can anyone see any glaringly obvoius mistakes!?
Thanks SO SO much for just reading this any help will be hugely appreciated.
how to clean pusher peak connection count? pls
I am building a system on the MERN stack (auction site).
the products of auction has following functionalities:
To achieve all this i am continuously emitting products times from backend (nodejs) using web sockets and set Interval (which triggers every second)
Is it bad approach?
Will it eventually slow down backend server ?
Thanks in Advance.
Dear all, I am experiencing this issue below. What I have done so far is to make sure both client and server use the same version of WebSocket. However, I am still having the problem. For what's worth, only when I am loading the page in my browser this issue is triggered and does not persist or blocking any communication as intended. But it appeared lately and before there was no issue in my app.
socket.io.js:1595 WebSocket connection to 'ws://127.0.0.1:8000/socket.io/?EIO=4&transport=websocket&sid=JRXfV0y5mrE7fBFEAAAA' failed: Invalid frame header
doOpen @ socket.io.js:1595
open @ socket.io.js:805
probe @ socket.io.js:2129
onOpen @ socket.io.js:2151
onHandshake @ socket.io.js:2212
onPacket @ socket.io.js:2171
Emitter.emit @ socket.io.js:628
onPacket @ socket.io.js:876
callback @ socket.io.js:1158
onData @ socket.io.js:1162
Emitter.emit @ socket.io.js:628
onLoad @ socket.io.js:1474
xhr.onreadystatechange @ socket.io.js:1397
DevTools failed to load source map: Could not load content for http://127.0.0.1:8000/socket.io.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
I am writing a code in Python to send three POST requests consecutively if certain conditions are met. The POST requests are sent to the FTX Exchange (which is a crypto exchange) and each request is a 'buy' order.
The second order is triggered as soon as the first is filled, and the third as soon as the second is filled. In order to speed up the code (I need the orders to be executed very close to each other in time), I am sending all POST requests to a subprocess (with multiprocessing.Process()
) and, instead of waiting for the request response, I wait for an update from a websocket connection to the wallet
channel that notifies each new filled order. This websocket connection is opened at the very beginning of the code, in a subprocess.
So, the timeline of the code is the following
channel 2. Loop until conditions are met 3. If True, exit loop and send first order through POST request 4. Wait until the first order is filled (i.e. update from the websocket) 5. Send second order through POST request 6. Wait until the second order is filled (i.e. update from the websocket) 7. Send third order through POST request 8. Wait until the third order is filled (i.e. update from the websocket) 9. Return "Orders submitted and filled"
I have the small problem that in step (4) the update from the websocket takes too much time to arrive (of the order of 1 second), while steps (6) and (8) are pretty fast (of the order of milliseconds).
It looks like the websocket connection is somehow sleeping before the steps (3)-(4) and it takes some time to receive messages but, as soon as the first message is received, all the subsequent messages arrive very fast. I am not a network expert... how can I avoid such delay in receiving the first message from the websocket?
I am pinging the websocket connection every 20 seconds and waiting for a pong within 10 seconds.
I have couple of Raspberry pi and i wish to get some statue (temp ,up-time, ...) out of them and display these info's in my simple angular application in real-time. My basic search lead me to use Websocket for this task
Each of my Pi's has a static IP address on the network BUT my angular app doesn't.
So my first thought is to setup a websocket server in each Pi and let angular to connect as wesocket client (in this case I have to know and store all my Pi's IP address in angular)
Is this best solution for this setup?
Title.
So i am using websocket to get data every second. Initially it is fine and no issues to my browser tab. After few seconds the slow activity of that particular tab starts showing. Like opening the inspect tab takes time. When navigating to "element" tab in inspect mode also takes time. But if i get the data once and stop the websocket and try working on that tab its all smooth. really need help to tackle the issue. The page whenever i visit becomes so damn slow over time thats its annoying.
Thinking of diving deep into socket.io, but I'm hoping to hear about people's positive and (more importantly) negative experiences using it.
Im currently using polygon forex websocket api.
And instead of parsing, retriving the hole response i would like to only parse, retrive the price.
I’ve googled for hours and in bash its very easy with curl awk and sed to extract specific info with the rest api.
But from my understanding these modules cannot be used within java or within commandline, Websocket does not support it?
Has anyone here had success with this or can point me in the right direction.
I would hope to extract the price with bash. but if not i probaly have to move to java :(
this is what the documentation say wscat -c wss://socket.polygon.io/crypto
then you type {"action":"auth","params":"apikey"}
then after that i type {"action":"subscribe","params":"XT.X:BTC-USD"}
then the data prints out like this.
< [{"ev":"XT","pair":"BTC-USD","p":46181.35,"t":1648933029045,"s":0.00017907,"c":[2],"i":"307817018","x":1,"r":1648933029054}]
How can i extract only the price of this json text?
Is it bad design to leave the socket variable as a public variable for ease of access for all of the files?
Hey r/Websocket!
We’ve used our extensive knowledge of WebSockets to write the definitive resource about the technology that opened the door to a truly realtime web: The Websocket Handbook.
We'd love to get your feedback on the handbook, and understand what people's experience is with WebSockets in general, including common pain points or interesting applications that you want to share, and what else you'd like to learn!
Hi, Currently I am working on a personal project where there are multiple clients in different pc and i have to send all clients some message. how would i do that? Is the REST API works in the case as the clients can only receive. but my doubt is this apps will be running in a pc desktop version, not web. so what would be the best approach? Thank you
Newbie to python but beyond "Hello world."
I am learning websockets and pulling in every ticker from the market at once with a websocket connection. (This is for fun to learn not to make a profitable program.) I understand the connection message T, subscription, trades, quotes, bars: (symbols) on the initial request to connect to the websocket. I am watching the data get pulled in. What is confusing to me is how fast the minute bars come in. I suppose it comes in serial, starts at the first symbol and sends the data, then the next, then the next then the next? My problem is each symbol that it gets the minute bar from, I do some work to it with a function, then another function then another, then another...up to 12 functions on that one symbol's minute data. Then I move to the next. Repeat. I keep getting a connection 1006 error, which I have looked up extensively but doesn't happen if I go to 5 stocks to look up. I can process the information for those five before a minute it appears then the minute pull/push stream starts again and repeats.
Overall, I am not looking for a code help. I am just trying to figure out the best way to handle pulling 3,000 symbols each minute, if possible and how fast that data can be pulled, and process them on the side? Do they have to come in serial? One at a time? Is the right thing to do put them in dataframes and handle them like that on the side as the data from the bars are not waiting for processing?
Basically, how do websockets send the data quickly?
Thanks.