1

I would like to convert HTML code to JavaScript. Currently I can send a message from the HTML file to a python server, which is then reversed and sent back to the HTML through socket io. I used this tutorial: https://tutorialedge.net/python/python-socket-io-tutorial/

What I want to do now is rather than send the message by clicking a button on a web page I can instead run a JavaScript file from the command line, so

node index.js

My index.js is below:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>
  const socket = io("http://localhost:8080");

  function sendMsg() {   
    socket.emit("message", "HELLO WORLD");
  }

  socket.on("message", function(data) {
     console.log(data);
  });
</script>

When running index.js I receive this error:

/home/name/Desktop/Research/server_practice/name/tutorialedge/js_communicate/index_1.js:1
(function (exports, require, module, __filename, __dirname) { <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>


SyntaxError: Unexpected token <
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3

In the error output, the caret is pointing at the second part of quotes:

socket.io/2.2.0/socket.io.js">
                            ^

I am pretty sure this is a syntax issue in combination with using socket io, but I am not sure what exactly is the problem. I believe I am using some sort of pseudo HTML/JavaScript code, which is why I am getting an error. I am new to JavaScript, but I need to use it because it contains APIs that I need.

For clarity, this is the working HTML code from the tutorial, index.html:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <button onClick="sendMsg()">Hit Me</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script>
      const socket = io("http://localhost:8080");

      function sendMsg() {   
        socket.emit("message", "HELLO WORLD");
      }

      socket.on("message", function(data) {
         console.log(data);
      });
    </script>
  </body>
</html>

And here is the python server code, server.py

from aiohttp import web
import socketio

# creates a new Async Socket IO Server
sio = socketio.AsyncServer()
# Creates a new Aiohttp Web Application
app = web.Application()
# Binds our Socket.IO server to our Web App
# instance
sio.attach(app)

# we can define aiohttp endpoints just as we normally
# would with no change
async def index(request):
    with open('index.html') as f:
        return web.Response(text=f.read(), content_type='text/html')

# If we wanted to create a new websocket endpoint,
# use this decorator, passing in the name of the
# event we wish to listen out for
@sio.on('message')
async def print_message(sid, message):
    print("Socket ID: " , sid)
    print(message)
    # await a successful emit of our reversed message
    # back to the client
    await sio.emit('message', message[::-1])

# We bind our aiohttp endpoint to our app
# router
app.router.add_get('/', index)

# We kick off our server
if __name__ == '__main__':
    web.run_app(app)

The end goal is to have multiple data streams from JavaScript being sent to Python to be analyzed and sent back to JavaScript to be outputted through an API.

W. Churchill
  • 346
  • 1
  • 7
  • 28

2 Answers2

1

Script tags don't work in node. You need to use require to import modules.

You can use the socket.io client module to connect to socket io using node. Note that you'll have to npm install it before use

Example connection code adapted from socket.io client readme:

var socket = require('socket.io-client')('http://localhost:8080');
socket.on('connect', function(){});

function sendMsg() {   
    socket.emit("message", "HELLO WORLD");
}

socket.on("message", function(data) {
    console.log(data);
});

socket.on('disconnect', function(){});
jro
  • 900
  • 1
  • 10
  • 21
  • I ran your suggestion for the client side, but when I run it nothing happens, there are no errors, but the "HELLO WORLD" message is not being sent to the the Python server from the JS script. I think I need to make a change to server.py, specifically around the following line, "with open('index.html') as f:" – W. Churchill Mar 31 '19 at 19:01
  • The code in my answer is meant to run server side. You can run it with `node index.js` – jro Mar 31 '19 at 22:11
  • Just to be clear, because I am running the JavaScript with node (node index.js) does that mean I am running JavaScript from a server? So I am basically now communicating between a python server and a JS server? I just want to make sure I fully understand what I am doing. – W. Churchill Mar 31 '19 at 23:41
  • Usually using node makes it a server, unless you are using electron, which is still client side. – jro Apr 01 '19 at 05:14
0

<script> tags are HTML tags - you can't have them in a JavaScript file. Just place your JavaScript:

const socket = io("http://localhost:8080");

function sendMsg() {   
    socket.emit("message", "HELLO WORLD");
}

socket.on("message", function(data) {
    console.log(data);
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79