Skip to content

Instantly share code, notes, and snippets.

@evscott
Created February 26, 2020 20:02
Show Gist options
  • Save evscott/8d6f9511ff84dfdc1f4d14788adb328f to your computer and use it in GitHub Desktop.
Save evscott/8d6f9511ff84dfdc1f4d14788adb328f to your computer and use it in GitHub Desktop.
from socket import *
import sys
import time
s = socket(AF_INET, SOCK_DGRAM)
serverAddress = (gethostname(), 12000)
for i in range(10):
msg = "Ping " + str(i)
s.sendto(msg.encode(), serverAddress)
start_time = time.time()
s.settimeout(1)
try:
message, address = s.recvfrom(1024)
except timeout:
print("RTT: timed out")
continue
elapsed_time = time.time() - start_time
print("Message:", message.decode(), "RTT.:", elapsed_time)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>My Website</h1>
<p>Some text...</p>
</body>
</html>
import random
from socket import *
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind((gethostname(), 12000))
while True:
rand = random.randint(0,10)
message, address = serverSocket.recvfrom(1024)
message = message.upper()
if rand < 4:
continue
serverSocket.sendto(message, address)
from socket import *
import sys
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((gethostname(), 8001))
print(gethostname())
serverSocket.listen(1)
while True:
print('Ready to serve...')
(connectionSocket, addr) = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1].decode()
f = open(filename[1:])
outputData = f.read()
connectionSocket.send("HTTP/1.1 200 OK\r\n".encode())
connectionSocket.send("Content-Type: text/html\r\n\r\n".encode())
for i in range(0, len(outputData)):
connectionSocket.send(outputData[i].encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
except IOError:
connectionSocket.send("HTTP/1.1 404 Not Found\r\n".encode())
connectionSocket.send("Content-Type: text/html\r\n\r\n".encode())
connectionSocket.send("404 Not Found".encode())
connectionSocket.close()
serverSocket.close()
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment