Flask's SocketIO isn't sending the right script to my client - javascript

I get this warning in Firefox Developer Tools:
The script from “https://js-game-tanks.herokuapp.com/socket.io/socket.io.js” was loaded even though its MIME type (“application/octet-stream”) is not a valid JavaScript MIME type.
and these errors:
SyntaxError: illegal character socket.io.js:1
ReferenceError: io is not defined test:10:20
My thinking is that I should be getting javascript not an octet-stream correct?
My HTML's JavaScript:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('any event', function(msg) {
console.log(msg);
});
</script>
Line 10 specifically is var socket = io();.
My Python will detect a connection with:
#socketio.on('connect')
def test_connect():
print('\n\nClient connected\n\n')
emit('we connected', {'data':'woot woot'})
and it will print client connected when I load my page.
And for context, this is deployed via Heroku and I'm using Gunicorn.
How do I resolve this? I am new to Socket.IO, so maybe I am just going about this all wrong.

Related

"Script error" reported in window.onerror without cross-site scripting

Almost every JS error I get using window.onerror is the unhelpful "Script error" message.
I have read everything I can find on this but it is always said it is caused by cross-site scripting, but there's none in my code.
Why do these unhelpful error messages appear and how can I replace them with the full messages that appear in the console?
As a test example, I created a minimal HTML/JS code pair. This is the HTML page, testpage.html:
<html>
<head></head>
<body>
<script src="/js/testpage.min.js"></script>
</body>
</html>
and JS script:
window.onerror = function(msg, url, lineNo, columnNo, error) {
// code goes here to generate log entry on the server
return true;
}
// generate illustrative sample error
var jsonData = "";
var data = JSON.parse(jsonData);
Running this, msg = "Script error" and other parameters are either null or zero. The Google DevTools console displays the full error:
Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at testpage.min.js:7
Any help towards being able to log the full error messages will be most welcome. I'm at a complete loss.
EDIT: Recast to make problem clearer.

Sending string from Javascript to Python code using Sockets

I am new to this area so forgive me if I've not explained myself well enough.
I am trying to set up a basic test where the html page that I've made (served using node.js) connects to my javascript template and that sends a string "hello world" to my python program.
I am connecting to port 3000 and using local host. My python module is capable of binding to the port but doesn't print any data that should be sent to the local host.
I am assuming the issue is oriented around the javascript side. Essentially all I am trying to do is have the webserver send the string as soon as the user clicks the button, although I am not sure how to establish this connection between my js template and html template. Even without a button the js fails to send the data.
I did use src = and used "alert("hello")" to check that the two templates were linked, which worked; as soon as the user opened the webpage they got a popup statement. But upon trying to send data using sockets, I'm not sure why no data is being sent from the webpage to my python program.
HTML:
<!DOCTYPE html>
<html>
<body>
<script type = "text/javascript" src = "backendrequest.js"></script>
<input id="clickMe" type="button" value="clickme" onclick="socketPress();" />
</body>
</html>
Javascript:
var net = require('net');
var client = new net.Socket();
client.connect(3000, 'localhost', function() {
console.log('Connected');
client.write('Hello World!');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});`
Python:
import socket
def Main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 3000
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
msg = s.recv()
s.close()
print (msg.decode('ascii'))
My main objective is to have the user print on python the data, in this case "hello world," coming from my local host, using sockets.
Any advice would be highly appreciated as I just want to know where I am going wrong.

Socket io - Wrong socket address calling

I have the following code on my static client side:
socket.io.js file calling:
<script src="https://rancher.mysite.com/mymodule/socket.io/socket.io.js"></script>
JS File content:
var socket = io.connect('https://rancher.mysite.com/', {
'path':'/mymodule/socket.io'
});
socket.on('mymodulefunction', function (msg) {
/// Do something (it doesn't call)
});
But socket.io tries to establish the connection with a different address. I can see this on browser developer tools and the address that he is trying to call in "Network" tab is: "https://rancher.mysite.com/socket.io" instead of "https://rancher.mysite.com/mymodule/socket.io".
Please, what am I doing wrong? I'm stuck in this problem for hours...

Javascript Sockets (failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET)

I am trying to create a simple program to send a message to a socket in plain text. The sender is a webpage in javascript using websocket and the server is a C program. I don't have any control over the C code but I have been assured by the codes owners that I can use simple javascript to send the message. My code is as follows:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
//initialize the websocket ws
var ws;
//Open the socket connection
function openSock() {
//test for Websocket compatibility in the browser
if ("WebSocket" in window) {
// log socket attempt
console.log("Attempting to open socket!");
//open web socket ws
ws = new WebSocket("ws://192.168.6.222:11000/echo");
} else { // else the browser doesn't support WebSocket
//Websocket is not supported
alert("APS NOT supported by your Browser!");
}
}
//send the command to socket ws
function sendCommand() {
console.log("Attempting to Send Message");
ws.send("your message here");
}
//close the socket ws
function closeSock() {
console.log("Closing Socket");
// close socket ws
ws.close();
}
</script>
</head>
<body>
<div id="sse">
<input type=submit value="open">
<input type=submit value="send">
<input type=submit value="close">
</div>
</body>
</html>
When I click the connect button I get this error:
WebSocket connection to 'ws://192.168.6.222:11000/echo' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
I have checked the firewall and the port seems to be open. After spending a fair amount of time troubleshooting the server (making sure it is running and on the network, etc.) I am wondering if I did something wrong with this client side code.
From my limited knowledge and the reading I have done this looks correct but any help is welcome.
This is probably super late but I just ran into a similar problem while using Django channels. I fixed it by adding a slash (/) at the end of the URL.
ws = new WebSocket("ws://192.168.6.222:11000/echo/");
How does the server side of the connection look like?
Maybe you are using a faulty WebSocket Lib which does not provide a valid handshake.
Because when testing the client against ws://echo.websocket.org everything seems to work perfectly fine. This strongly suggests that the websocket client is not source of the problem.
Make sure that your queue is running properly, in my case that was the issue

Calling Thrift python server from thrift javascript client (CORS) issue (FIXED using browser extension)

I am trying to connect to python thrift server from a javacript thrift client. Currently I am just using a tutorial code on which I will build later. The python server code can be found here -> Python server code
The javscript code is as follows
thriftCall:function() {
var transport = new Thrift.Transport("http://localhost:30303/pythonImpl/pythonServer");
var protocol = new Thrift.Protocol(transport);
var client = new HelloWorldClient(protocol);
try {
result = client.ping();
cc.log(result);
result = client.sayHello();
cc.log(result);
result = client.sayMsg(HELLO_IN_KOREAN);
cc.log(result);
}catch(ouch){
cc.log("Problem!!!");
}
}
When I try to connect I get the following error message on server
D:\Game Component Integration\Project\thriftPyTest\pythonImpl>pythonServer.py
Starting python server...
ERROR:thrift.server.TServer:
Traceback (most recent call last):
File "build\bdist.win32\egg\thrift\server\TServer.py", line 88, in serve self.processor.process(iprot, oprot)
File "../gen-py\helloworld\HelloWorld.py", line 133, in process (name, type, seqid) = iprot.readMessageBegin()
File "build\bdist.win32\egg\thrift\protocol\TBinaryProtocol.py", line 140, in readMessageBegin
name = self.trans.readAll(sz)
File "build\bdist.win32\egg\thrift\transport\TTransport.py", line 58, in readAll
chunk = self.read(sz - have)
File "build\bdist.win32\egg\thrift\transport\TTransport.py", line 159, in read
self.__rbuf = StringIO(self.__trans.read(max(sz, self.__rbuf_size)))
File "build\bdist.win32\egg\thrift\transport\TSocket.py", line 105, in read
buff = self.handle.recv(sz)
MemoryError
I have no idea how to go about this issue . Same server works fine when called from python client. Any help or leads will really be appreciated.
Update :
I had to use a JSON protocol for python
handler = HelloWorldHandler()
processor = HelloWorld.Processor(handler)
transport = TSocket.TServerSocket(port=30303)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TJSONProtocol.TJSONProtocolFactory() #pfactory = TBinaryProtocol.TBinaryProtocolFactory()
port = 30303
#server = THttpServer.THttpServer(processor, transport, tfactory, pfactory)
server = THttpServer.THttpServer(processor, ("localhost", port), pfactory)
print "Starting python server..."
server.serve()
print "done!"
So now js client CAN connect but I am getting this error
http://localhost:30303//pythonImpl/pythonServer. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
I guess I have to add header while sending response from python server . Any Idea how ???
Thanks.
Udpate: Tried many things , didnt work . So just so that it would work , I simply added chrome extension that solves CORS issue. Extension can be found here . Yet I would welcome any idea on fixing this issue in code itself.

Categories