5110_assignment3 - MaxGolden/Personal_Blogs GitHub Wiki

Assignment3

from socket import *
import sys  # In order to terminate the program

# Create a TCP/IP socket
serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket

serverPort = 15000
BUFFER_SIZE = 20480  # in case out of range in the list index
print('hostname is: ', gethostname())
# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))

# Listen for incoming connections
serverSocket.listen(1)
while True:
    # Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept()
    print('Connection address:', addr)

    try:
        message = connectionSocket.recv(BUFFER_SIZE)
        print('Message is: ', message)

        filename = message.split()[1]
        print('File name is: ', filename)

        f = open(filename[1:])
        outputdata = f.read()

        # Send one HTTP header line into socket
        connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n".encode())

        # Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i].encode())
        connectionSocket.send("\r\n".encode())

        connectionSocket.close()

    except IOError:
        # Send response message for file not found
        connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n".encode())
        connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n".encode())

        # Close client socket
        connectionSocket.close()

serverSocket.close()

sys.exit()
# Terminate the program after sending the corresponding data
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
    <div>
        Hello, Max, you succeeded connect to the <b>index.html</b> page.
    </div>
</body>
</html>
localhost = "127.0.0.1"
serverPort = 15000

serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverSocket.bind((localhost, serverPort))

print("Multi-thread Server Started")
print("Waiting for clients ...")

while True:
    serverSocket.listen(1)
    connectionSocket, addr = serverSocket.accept()
    new_thread = ClientThread(addr, connectionSocket)
    new_thread.start()
class ClientThread(threading.Thread):

    def __init__(self, client_address, client_socket):
        threading.Thread.__init__(self)
        self.csocket = client_socket
        print("New connection from client: ", client_address)

    def run(self):
        print("Connection from : ", addr)
        message = ''
        while True:
            message_rec = self.csocket.recv(1024)
            message = message_rec.decode()
            print("Message from client: '", message, "'")
            self.csocket.send(bytes(message, 'UTF-8'))
class ClientThread(threading.Thread):

    def __init__(self, client_address, client_socket):
        threading.Thread.__init__(self)
        self.csocket = client_socket
        print("New connection from client: ", client_address)

    def run(self):
        while True:
            try:
                # data received from client
                message_rec = self.csocket.recv(1024)
                filename = message_rec.split()[1]
                print('The file name you typed is: ', filename)

                f = open(filename[1:])
                outputdata = f.read()

                # Send one HTTP header line into socket
                self.csocket.send("HTTP/1.1 200 OK\r\n\r\n".encode())
                print("file found succeeded!")
                # Send the content of the requested file to the client
                for i in range(0, len(outputdata)):
                    self.csocket.send(outputdata[i].encode())
                self.csocket.send("\r\n".encode())
                self.csocket.close()

            except IOError:
                # Send response message for file not found
                self.csocket.send("HTTP/1.1 404 Not Found\r\n\r\n".encode())
                self.csocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n".encode())
                print("404(file) Not Found, please retry ...")
                # Close client socket
                self.csocket.close()
import socket

server = "127.0.0.1"
serverPort = 15000
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_address = (server, serverPort)
client.connect(server_address)

request_header = 'GET /index.html HTTP/1.1\r\nHost: localhost:15000\r\n\r\n'
client.send(request_header.encode())

response = ''
while True:
    message_rec = client.recv(1024)
    message = message_rec.decode()
    if not message_rec:
        break
    response += message

print(response)
client.close()
⚠️ **GitHub.com Fallback** ⚠️