自顶向下计算机网络第二章答案,计算机网络的自顶向下方法第2章socket编程作业web服务器应答,第二章,套,接字,Web,答案...

#改为Python3格式

#import socket module

from socket import *

serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a sever socket

serverPort = 80

serverSocket.bind(("", serverPort))

serverSocket.listen(1)

while True:

#Establish the connection

print('Ready to serve...')

connectionSocket, addr = serverSocket.accept()

try:

message = connectionSocket.recv(1024)

filename = message.split()[1]

f = open(filename[1:])

outputdata = f.read()

f.close()

#Send one HTTP header line into socket

outputdata = 'HTTP/1.1 200 OK\r\n\r\n' + outputdata

#Send the content of the requested file to the client

for i in range(0, len(outputdata)):

connectionSocket.send(outputdata[i].encode())

connectionSocket.close()

print("OK!")

except IOError:

#Send response message for file not found

outputdata = 'HTTP/1.1 404 Not Found\r\n\r\n'

#Close client socket

for i in range(0, len(outputdata)):

connectionSocket.send(outputdata[i].encode())

connectionSocket.close()

serverSocket.close()

#改为Python3格式

#import socket module

from socket import *

import threading

def webProcess(connectionSocket):

try:

message = connectionSocket.recv(1024)

filename = message.split()[1]

f = open(filename[1:], "rb")

outputdata = f.read()

outputdata = outputdata.decode()

f.close()

#Send one HTTP header line into socket

outputdata = 'HTTP/1.1 200 OK\r\n\r\n' + outputdata

#Send the content of the requested file to the client

for i in range(0, len(outputdata)):

connectionSocket.send(outputdata[i].encode())

connectionSocket.close()

print("OK!")

except IOError:

#Send response message for file not found

outputdata = 'HTTP/1.1 404 Not Found\r\n\r\n'

#Close client socket

for i in range(0, len(outputdata)):

connectionSocket.send(outputdata[i].encode())

connectionSocket.close()

serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a sever socket

serverPort = 80

serverSocket.bind(("", serverPort))

serverSocket.listen(10)

while True:

#Establish the connection

print('Ready to serve...')

connectionSocket, addr = serverSocket.accept()

thread = threading.Thread(target = webProcess, args = (connectionSocket, ))

thread.start()

serverSocket.close()

#Python3格式

from socket import *

serverName = '127.0.0.1'

serverPort = 80

clientSocket = socket(AF_INET, SOCK_STREAM)

clientSocket.connect((serverName, serverPort))

outputdata = 'GET /hello.html HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n'

clientSocket.send(outputdata.encode())

data = 1

while data:

data = clientSocket.recv(1024)

print(data.decode(), end = '')

clientSocket.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值