Simple Browser and Server in Python vs. JS

By Sheldon L Published at 2020-02-11 Updated at 2020-02-11


Python Browser

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/page1.htm HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)

while True:
    data = mysock.recv(512)
    if len(data) < 1:
        break
    print(data.decode(), end='')

mysock.close()

Python Server

# https://docs.python.org/3/howto/sockets.html
# https://stackoverflow.com/questions/8627986/how-to-keep-a-socket-open-until-client-closes-it
# https://stackoverflow.com/questions/10091271/how-can-i-implement-a-simple-web-server-using-python-without-using-any-libraries


from socket import *


def createServer():
    serversocket = socket(AF_INET, SOCK_STREAM)
    try:
        serversocket.bind(('localhost', 9000))
        serversocket.listen(5)
        while True:
            (clientsocket, address) = serversocket.accept()

            rd = clientsocket.recv(5000).decode()
            pieces = rd.split("\n")
            if len(pieces) > 0:
                print(pieces[0])

            data = "HTTP/1.1 200 OK\r\n"
            data += "Content-Type: text/html; charset=utf-8\r\n"
            data += "\r\n"
            data += "<html><body>Hello World</body></html>\r\n\r\n"
            clientsocket.sendall(data.encode())
            clientsocket.shutdown(SHUT_WR)

    except KeyboardInterrupt:
        print("\nShutting down...\n")
    except Exception as exc:
        print("Error:\n")
        print(exc)

    serversocket.close()


print('Access http://localhost:9000')
createServer()
const http = require('http')
const path = require('path')
const fs = require('fs')

const server = http.createServer(
  (req, res) => {
    console.log(req.url)

    if (req.url === '/') {
      fs.readFile(
        path.join(__dirname, 'public', 'index.html'),
        'utf8',
        (err, content) => {
          if (err) throw err;
          res.writeHead(200, {'Content-Type': 'text/html'})
          res.end(<html><body>Hello World</body></html>);
        }
      )
    }
  }
)

const PORT = process.env.PORT || 8080

server.listen(PORT, () => console.log(`Server running on ${PORT}...`))

Run python client after server is setup

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('127.0.0.1', 9000))
cmd = 'GET http://127.0.0.1/whatever.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)

while True:
  data = mysock.recv(512)
  if len(data) < 1:
    break
  print(data.decode(), end='')

mysock.close()
import urllib.request

fhand = urllib.request.urlopen('http://127.0.0.1:9000/whatever.txt')
for line in fhand:
  print(line.decode().strip())