开始补网络的欠账…
这个也是《计算机网络—自顶向下方法》的实验二,后面还有多线程服务器。
这个服务器程序采取的传输层协议是TCP,TCP和UDP的区别就不赘述了,在socket编程上也有区别体现。
局域网ip的获取方法:
终端命令:ifconfig | grep "inet"
代码:
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM) #TCP socket
#Prepare a sever socket
#Fill in start
serverPort = 12000 #服务器需要指定端口号,客户端不用,OS会自动分配端口号
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort)) #将socket和端口绑定
serverSocket.listen(1)
#Fill in end
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();
#Send one HTTP header line into socket
#Fill in start
header = ' HTTP/1.1 200 OK\nConnection: close\nContent-Type: text/html\nContent-Length: %d\n\n' % (len(outputdata))
connectionSocket.send(header.encode())
#Fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.close()
except IOError: #文件不存在发送404 Not Found
#Send response message for file not found
#Fill in start
#Fill in end
header = ' HTTP/1.1 404 Found'
connectionSocket.send(header.encode())
#Close client socket
#Fill in start
#Fill in end
serverSocket.close()
关于socket.listen:
作用是聆听来自客户的TCP最大连接请求,最小为1;
如果是多线程web服务器,listen需要大于1。
结果验证:
打开浏览器,输入http://192.168.0.104:12000/HelloWorld.html
连着同一个wifi的其他终端也可以访问,4G就不行了。