How to connect to django channel socket? - websocket

I followed the tutorial on the official site of the django channels. Everything is fine. But now, how do I connect to the ongoing socket and push message to the group in the server side (i.e. via django) ?
In the tutorial, following line of code in the js opens up a WebSocket connection simply by calling the WebSocket constructor:
var chatSocket = new WebSocket('ws://' + window.location.host + '/ws/chat/' + roomName + '/');
And I want to connect to the same socket in the server side. I tried this:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('ws://127.0.0.1/ws/chat/2', 6379))
but I get error saying
socket.gaierror: [Errno -2] Name or service not known
I am a complete beginner in socket programming, and apologize if there is anything minor that I may have skipped.

Related

Vercel "This Serverless Function has crashed" with simple GraphQL request from SvelteKit app

I am getting frequent, seemingly random errors on initial page load. I think the problem has to do with Vercel Serverless Functions.
I regularly get this error on the website itself:
Full log from Vercel:
[GET] /
14:54:19:39
2022-07-21T12:54:19.426Z 3a175b6b-396b-45d5-b1a1-46072201cd6a ERROR Unhandled Promise Rejection
{"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"FetchError: request to
https://api-eu-central-1.graphcms.com/v2/cl2k6hi1809a401xk4hd3h5zj/master failed, reason:
Client network socket disconnected before secure TLS connection was
established","reason":{"errorType":"FetchError","errorMessage":"request to https://api-
eu-central-1.graphcms.com/v2/cl2k6hi1809a401xk4hd3h5zj/master failed, reason: Client
network socket disconnected before secure TLS connection was
established","code":"ECONNRESET","message":"request to https://api-eu-central-
1.graphcms.com/v2/cl2k6hi1809a401xk4hd3h5zj/master failed, reason: Client network socket
disconnected before secure TLS connection was
established","type":"system","errno":"ECONNRESET","stack":["FetchError: request to
https://api-eu-central-1.graphcms.com/v2/cl2k6hi1809a401xk4hd3h5zj/master failed, reason:
Client network socket disconnected before secure TLS connection was established"," at
ClientRequest.<anonymous> (/var/task/index.js:7892:18)"," at ClientRequest.emit
(node:events:527:28)"," at TLSSocket.socketErrorListener (node:_http_client:454:9)","
at TLSSocket.emit (node:events:527:28)"," at emitErrorNT (node:internal/streams
/destroy:157:8)"," at emitErrorCloseNT (node:internal/streams/destroy:122:3)"," at
processTicksAndRejections (node:internal/process/task_queues:83:21)"]},"promise":
{},"stack":["Runtime.UnhandledPromiseRejection: FetchError: request to https://api-eu-
central-1.graphcms.com/v2/cl2k6hi1809a401xk4hd3h5zj/master failed, reason: Client network
socket disconnected before secure TLS connection was established"," at process.
<anonymous> (file:///var/runtime/index.mjs:775:15)"," at process.emit
(node:events:539:35)"," at emit (node:internal/process/promises:140:20)"," at
processPromiseRejections (node:internal/process/promises:274:27)"," at
processTicksAndRejections (node:internal/process/task_queues:97:32)"]}[ERROR]
[1658408059427] LAMBDA_RUNTIME Failed to post handler success response. Http response
code: 400.RequestId: 2a0597b4-6684-4f2a-a724-2333b4f9332d Error: Runtime exited with
error: exit status 128Runtime.ExitError
Example code from SvelteKit endpoint:
import {client} from '$lib/js/graphql-client'
import {projectsQuery} from '$lib/js/graphql-queries'
export async function get() {
let sm = 640;
let md = 768;
let lg = 1024;
let xl = 1280;
let xxl = 1536;
const variables = {sm, md, lg, xl, xxl}
const {projects} = await client.request(projectsQuery, variables)
return {
body: {
projects, sm, md, lg, xl, xxl
}
}
}
Now, other people seem to have similar problems:
Vercel + NextJS : Client network socket disconnected before secure TLS connection was established - Help - Fauna Forums
node.js - Getting a 504/502 error on api requests in Nextjs deployed on Vercel - Stack Overflow
[AWS-Lambda] - NetworkingError: Client network socket disconnected before secure TLS connection was established · Issue #3591 · aws/aws-sdk-js · GitHub
Especially the last link makes it seem like the source of the problem lies in AWS Lambda. I do not expect a magic bullet, but I do want to make sure the problem is in fact what I think it is (and not a mistake in my code).
Has anyone found any workarounds? Ways of minimizing the probability of these functions crashing?
I had to add index.js in vercel.json. See this link for more information.

Modify server response using node http proxy

I am a beginner to node js and this is my first post in here so apologies if this is a stupid question.
The problem I need to solve is to change information in an HTTPS server response before it hits the client. The reason is that my my client (Im developing a GARMIN sports watch application) cannot read the server response as the body data format differs from the content_type as defined in the response header. I have no means of impacting the server code and on the client I am stuck as well, Garmin has acknowledged it should be fixed but have not put it on priority.
I guess that leaves me with having to implement my own http proxy that I can connect in between the client and server to change either the header or the data format in the server response.
I have browsed around a bit and also played around a bit with node-http-proxy but I am not sure what is the best solution approach. Basically, the SERVER expects HTTPS comms, and preferably I also want secured comms between the PROXY and the CLIENT (since they will exchange user credentials).
I guess my first question is if this is a possible use case:
CLIENT -> (HTTPS_POST_req) -> PROXY -> (HTTPS_POST_req) -> SERVER
SERVER -> (HTTPS_resp) -> PROXY -> (modified_HTTPS_resp) -> CLIENT
I took a quick shot at it using node-http-proxy sample code but got stuck. What I did was to create an http server on localhost and a proxy server that would proxy the request to SERVER.
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
http.createServer(function(req, res) {
console.log('incoming request');
console.log('URL:' + req.url);
console.log('Method:' + req.method);
console.log('Headers:' + JSON.stringify(req.headers));
proxy.web(req, res, { target:'SERVER ADDRESS HERE' });
}).listen(8888, () => {
console.log("Waiting for requests...");
});
From the console I can see the incoming request and also read the url, headers and method but then after a short while I get this:
Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 80
}
I have no idea why something want to connect to localhost on port 80.
Perhaps this approach will never work for HTTPS/SSL traffic? For instance, do I have to setup my own server certificate to do this or can node-http-proxy handle it "under the hood"? Need a bit of help, please.
//Fredrik

How to establish web socket on server side for chat implementation?

If i don't have server details then who will establish or install the web socket connection? Can admin (who handle our host) establish connection and provide me the URL of websocket to use in android or angular code?
Is this necessary to write code in php?
I expect server admin install and configure web socket and provide to use in chat module.
Web admin(Ops) can help create the domain name but you have to write serverside code to handle websocket connection. You can use any programming language that supports websocket. for example,
nodejs - https://github.com/websockets/ws
java - https://docs.oracle.com/javaee/7/api/javax/websocket/package-summary.html
With java websocket you simply can define ServerEndpoint and deploy the war(web archive) to any host or cloud provider(Amazon cloud, google cloud etc),
#ServerEndpoint("/chat/{clientId}")
public class MyWebsocketServer {
#OnMessage
public String handleMessage(#PathParam("clientId") String clientId,
String message,
Session session) {
System.out.println("chat message: " + clientId + "/" +message);
return "hi how are you doing?";
}
}
Now, with javascript as a client your code to establish WebSocket connection would be:
var clientId = Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36);
var webSocket = new WebSocket("ws://localhost:8080/my-app/chat/" + clientId);
localhost means I'm running both Server and Client in same host, in your case serving host might be www.mike-simons.com/chat while client running on phone
Example: https://github.com/duwamish-os/chat-server_websocket-java

Websocket closing issue

I am working on web application for client side which is user websocket connection to send/receive data.
Here is my problem.
If some parameter change on client side, I want to close my web socket connection and initiate new connection with new paramaeters.
I tried to close web socket connection bu using close(). But when I checked my browser console, websocket status is always 2.
Please help me to resolve this.
I am not completely sure of what problem you have, but if you set a handler for onclose, it will be triggered when you call close.
var ws = new WebSocket('wss://wss://echo.websocket.org');
ws.onclose=function(){
alert('The websocket just closed, readyState: ' + ws.readyState);
}
Demo: http://jsfiddle.net/6kh20bdy/
ReadyState 3 means closed: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Constants

open websocket connection firefox addon

Is it possible for a firefox addon to establish a websocket connections?
When I try:
var wsUri = "ws://echo.websocket.org/";
var ws = gBrowser.contentWindow.window.WebSocket ||
gBrowser.contentWindow.window.MozWebSocket;
var websocket = new ws(wsUri);
In the Error Console the message says
Error: Firefox can't establish a connection to the server at ws://echo.websocket.org/.
Currently, it seems the only option is to proxy your WebSocket messages through a PageWorker. There is an example of how to do this on this website:
http://austinhartzheim.me/blog/4/websockets-firefox-sdk-addons/

Resources