I’m trying to create a simple game on javascript where people can play together, I had issues on the communication between the client and the server using a JSON file.
Without doing any changing on my code and starting the code again I saw this error on the chrome console:
SyntaxError: Unexpected token 'I', "Invalid JS"... is not valid JSON
and this error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Going in the server code, in the python console this has been printed:
Uncaught exception GET /game (::1)
HTTPServerRequest(protocol='http', host='localhost:1234', method='GET', uri='/game', version='HTTP/1.1', remote_ip='::1')
Traceback (most recent call last):
File "C:UsersLucaAppDataLocalProgramsPythonPython312Libsite-packagestornadowebsocket.py", line 631, in _run_callback
result = callback(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:UsersLucaDocumentsScriptsGiocoOnlineserver_5.py", line 36, in on_message
contenutoFile = json.load(f)
^^^^^^^^^^^^
File "C:UsersLucaAppDataLocalProgramsPythonPython312Libjson__init__.py", line 293, in load
return loads(fp.read(),
^^^^^^^^^^^^^^^^
File "C:UsersLucaAppDataLocalProgramsPythonPython312Libjson__init__.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersLucaAppDataLocalProgramsPythonPython312Libjsondecoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersLucaAppDataLocalProgramsPythonPython312Libjsondecoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Followed by a ton of errors like these:
500 GET /json?ts=2024-04-25T18:51:24.390Z (::1) 5.00ms
500 GET /json?ts=2024-04-25T18:51:24.401Z (::1) 1.00ms
500 GET /json?ts=2024-04-25T18:51:24.422Z (::1) 2.00ms
500 GET /json?ts=2024-04-25T18:51:24.434Z (::1) 2.00ms
500 GET /json?ts=2024-04-25T18:51:24.448Z (::1) 2.00ms
500 GET /json?ts=2024-04-25T18:51:24.464Z (::1) 2.00ms
500 GET /json?ts=2024-04-25T18:51:24.481Z (::1) 3.00ms
500 GET /json?ts=2024-04-25T18:51:24.496Z (::1) 1.00ms
500 GET /json?ts=2024-04-25T18:51:24.513Z (::1) 2.00ms
This is the server code
import tornado.ioloop
import tornado.web
import tornado.websocket
import json
clients = []
players = []
corrispondenza = ["P1", "P2"]
class JsonHandler(tornado.web.RequestHandler):
def get(self):
self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
try:
with open("C:/Users/Luca/Documents/Scripts/GiocoOnline/base.json", "r") as file:
data = json.load(file)
self.write(data)
except FileNotFoundError:
# Handle file not found error
self.set_status(404)
self.write("File not found")
except json.JSONDecodeError:
# Handle invalid JSON format
self.set_status(500)
self.write("Invalid JSON format in file")
class GameHandler(tornado.websocket.WebSocketHandler):
def open(self):
clients.append(self)
self.id = clients.index(self)
self.write_message(json.dumps({"clientId" : self.id}))
def on_message(self, player):
player = json.loads(player)
f = open("C:/Users/Luca/Documents/Scripts/GiocoOnline/base.json", "r+")
contenutoFile = json.load(f)
contenutoFile[corrispondenza[self.id]] = player
f.close()
with open ("C:/Users/Luca/Documents/Scripts/GiocoOnline/base.json", "w") as file:
json.dump(contenutoFile, file)
def on_close(self):
x = self.id
clients.remove(self)
for i in range(x, len(clients) - x):
clients[i].id -= 1
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("client_5.html")
# Create a Tornado application with routing
application = tornado.web.Application([
(r"/", MainHandler),
(r"/game", GameHandler),
(r"/json", JsonHandler),
])
if __name__ == "__main__":
application.listen(1234)
tornado.ioloop.IOLoop.current().start()
This is the part of the client code, where i get the error
function sendData() {
console.log(JSON.stringify(player))
ws.send(JSON.stringify(player))
}
let getData = async () => {
let ts = (new Date()).toISOString();
let response = await fetch("http://localhost:1234/json?ts=" + ts)
data = await response.json()
}
All the server appears when i connect a client to the server.
I already tried to check if the json exists and i tried to create another one form zero thinking that the file could be corrupted.
I have never used tornado or javascript before.
Some words are in italian so if you need a translation please ask.
Thank you 🙂