socket编程

HTTP

WebServer下载

client

from socket import *
import sys

#serverName = sys.argv[1]
#serverPort = int(sys.argv[2])
#filename = sys.argv[3]
serverName = '123.60.221.93'
serverPort = 12000
filename = 'a.html'

clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverName, serverPort))

header = 'GET /{} HTTP/1.1'.format(filename)
header += '\r\n'
# print(header)

clientSocket.send(header.encode())

modifiedfilename = clientSocket.recv(1024).decode()
#print(modifiedfilename)

with open(filename, 'w') as file:
    file.write(modifiedfilename)
with open(filename, 'r') as file:
    lines = file.readlines()
with open(filename, 'w') as file:
    file.writelines(lines[2:-1])

clientSocket.close()

server

单线程处理

#import socket module
from socket import *
import sys # In order to terminate the program
serverSocket = socket(AF_INET, SOCK_STREAM) # TCP 连接

#Prepare a sever socket
#Fill in start

serverPort = 12000
serverSocket.bind(('',serverPort))
serverSocket.listen(1)

#Fill in end
while True:
    #Establish the connection
    print('Ready to serve...')

    connectionSocket, addr = serverSocket.accept() #Fill n start         #Fill in end
    #print(connectionSocket)
    #print(addr)
    try:
        message = connectionSocket.recv(1024).decode()#Fill in start        #Fill in end
        filename = message.split()[1] # eg: Get /filename HTTP/1.1\r\n   get /filename
        f = open(filename[1:]) # get filename
        outputdata = f.read()#Fill in start    #Fill in end
        #Send one HTTP header line into socket
        #Fill in start

       # head = message.split()[2]
       # head = head.rstrip(\r\n)
       # head +=  200 OK\r\n
        parts = message.split()
        # 获取HTTP版本
        http_version = parts[2] if len(parts) > 2 else 'HTTP/1.1'
        header = '{} 200 OK\r\n'.format(http_version)
        #header += 'Content-Length: {}\r\n'.format(len(outputdata))
        header += '\r\n'

        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.send(\r\n.encode())

        connectionSocket.close()
    except IOError:
    #Send response message for file not found

        parts = message.split()
        # 获取HTTP版本
        http_version = parts[2] if len(parts) > 2 else 'HTTP/1.1'
        header = '{} 404 Not Found\r\n\r\n'.format(http_version)
        connectionSocket.send(header.encode())

    #Close client socket

    connectionSocket.close()

serverSocket.close()
sys.exit()#Terminate the program after sending the corresponding dat

多线程处理

from socket import *
import sys # In order to terminate the program
import threading
import time
serverSocket = socket(AF_INET, SOCK_STREAM) # TCP 连接

serverPort = 12000
serverSocket.bind((\'\',serverPort))
serverSocket.listen(5)

def connect(connectionSocket, addr):
while True:
# connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024).decode()#Fill in start #Fill in end
filename = message.split()[1] # eg: Get /filename HTTP/1.1\\r\\n get /filename
f = open(filename[1:]) # get filename
outputdata = f.read()#Fill in start #Fill in end
#Send one HTTP header line into socket
# head = message.split()[2]
# head = head.rstrip(\\r\\n)
# head +=  200 OK\\r\\n
parts = message.split()
# 获取HTTP版本
http_version = parts[2] if len(parts) > 2 else \'HTTP/1.1\'
header = \'{} 200 OK\\r\\n\'.format(http_version)
#header += \'Content-Length: {}\\r\\n\'.format(len(outputdata))
header += \'\\r\\n\'
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.send(\\r\\n.encode())
connectionSocket.close()
except IOError:
        parts = message.split()
        http_version = parts[2] if len(parts) > 2 else 'HTTP/1.1'
        header = '{} 404 Not Found\r\n\r\n'.format(http_version)
        connectionSocket.send(header.encode())
    connectionSocket.close()

def create_connect_thread():
connectionSocket, addr = serverSocket.accept()
t = threading.Thread(target=connect,args=(connectionSocket, addr))
t.start()
t.join()

if **name** == **main**:
while True:
print(\'Ready to serve…\')
create_connect_thread()

serverSocket.close()
sys.exit()#Terminate the program after sending the corresponding dat

BUG:

采用多线程的server,虽然能正常运行,但是会出现bug在运行是,猜测是在线程未执行完就关闭了连接

root@hcss-ecs-288a:~/VideoStreamingCode# python3 Web_parallel_server.py
Ready to serve...
Ready to serve...
Exception in thread Thread-1 (connect):
Traceback (most recent call last):
  File /root/VideoStreamingCode/Web_parallel_server.py, line 19, in connect
    message = connectionSocket.recv(1024).decode()#Fill in start        #Fill in end
OSError: [Errno 9] Bad file descriptor

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File /usr/lib/python3.10/threading.py, line 1016, in _bootstrap_inner
    self.run()
  File /usr/lib/python3.10/threading.py, line 953, in run
    self._target(*self._args, **self._kwargs)
  File /root/VideoStreamingCode/Web_parallel_server.py, line 51, in connect
    connectionSocket.send(header.encode())
OSError: [Errno 9] Bad file descriptor

UDPPinger

UDPPinger下载

client

from socket import *
import sys
import time

#serverName = sys.argv[1]
#serverName = '123.60.221.93'
serverName = '127.0.0.1'
serverPort = 12000

clientSocket = socket(AF_INET, SOCK_DGRAM)
clientSocket.settimeout(1)
message = input('Input lowercase sentence:')
try_number = 10

timeout_cnt = 0
max_time = -1
min_time = 100
avg_time = 0

for _ in range(try_number):
    try:
        start_time = time.time()
        clientSocket.sendto(message.encode(),(serverName,serverPort))
        backmessage, serverAddress = clientSocket.recvfrom(2048)
        end_time = time.time()
        RTT = end_time - start_time
        if RTT > max_time:
            max_time = RTT
        elif RTT < min_time:
            min_time = RTT
        avg_time += RTT
        print(backmessage,running time:{:.6} s.format(RTT))
    except TimeoutError:
        timeout_cnt = timeout_cnt + 1
        print(connect timeout)
        # print(message,running time,RTT,s)
print(loss rate:{}.format(timeout_cnt/10))
print(max time:{:.6}.format(max_time))
print(min time:{:.6}.format(min_time))
print(avg time:{:.6}.format(avg_time/(try_number - timeout_cnt)))

clientSocket.close()

server

# UDPPingerServer.py
# We will need the following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('', 12000))
while True:
    # Generate random number in the range of 0 to 10
    rand = random.randint(0, 10)
    # Receive the client packet along with the address it is coming from
    message, address = serverSocket.recvfrom(1024)
    # Capitalize the message from the client
    message = message.upper()
    # If rand is less is than 4, we consider the packet lost and do not respond
    if rand < 4:
        continue
    # Otherwise, the server responds
    serverSocket.sendto(message, address)

SMTP

client


from socket import *
import ssl

msg = \r\n I love computer networks!
endmsg = \r\n.\r\n

Choose a mail server (e.g. Google mail server) and call it mailserver

mailserver = 'smtp.qq.com'
serverPort = 25

Create socket called clientSocket and establish a TCP connection with mailserver

clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((mailserver,serverPort))

recv = clientSocket.recv(1024).decode()
print(recv)

if recv[:3] != '220':
    print('220 reply not received from server.')

# Start SSL/TLS connection
# clientSocket = ssl.wrap_socket(clientSocket)

# Send HELO command and print server response.
heloCommand = 'HELO Alice\r\n'
clientSocket.send(heloCommand.encode())
recv1 = clientSocket.recv(1024).decode()
print(recv1)

if recv1[:3] != '250':
    print('250 reply not received from server.')

# Send MAIL FROM command and print server response.
fromCommand = 'MAIL FROM: <Alice>'
clientSocket.send(fromCommand.encode())
recv2 = clientSocket.recv(1024).decode()
print(recv2)

# Send RCPT TO command and print server response.
rcptCommand = 'RCPT TO: <qianyouwu@qq.com>'
clientSocket.send(rcptCommand.encode())
recv3 = clientSocket.recv(1024).decode()
print(recv3)

# Send DATA command and print server response.
clientSocket.send('DATA'.encode())
recv4 = clientSocket.recv(1024).decode()
print(recv4)

# Send message data.

# file_path = data.txt
# 
# try:
#     with open(file_path, 'r') as file:
#         data = file.read()
# except FileNotFoundError:
#     print(File not found. Please check the file path.)
# except Exception as e:
#     print(An error occurred:, e)
# print(data)
# clientSocket.send(data.encode())
print(msg)
clientSocket.send(msg.encode())

# Message ends with a single period.
clientSocket.send('endmsg'.encode())
recv5 = clientSocket.recv(1024).decode()
print(recv5)

# Send QUIT command and get server response.
clientSocket.send('QUIT\r\n'.encode())
recv6 = clientSocket.recv(1024).decode()
print(recv6)

clientSocket.close()

ssl_client

from socket import *
import ssl
import base64

msg = \r\n I love computer networks!
endmsg = \r\n.\r\n

# Choose a mail server (e.g. Google mail server) and call it mailserver
mailserver = ('smtp.qq.com',465)

# Create socket called clientSocket and establish a TCP connection with mailserver
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect(mailserver)

# Start SSL/TLS connection
context = ssl.create_default_context()
secured_socket = context.wrap_socket(clientSocket, server_hostname='smtp.qq.com')

# Send EHLO command and print server response.
ehloCommand = 'EHLO gmail.com\r\n'
secured_socket.sendall(ehloCommand.encode())
recv7 = secured_socket.recv(1024).decode()
print(recv7)

# If authentication is required, send AUTH command here.
# Send AUTH LOGIN command
authCommand = 'AUTH LOGIN\r\n'
secured_socket.sendall(authCommand.encode())
recv_auth = secured_socket.recv(1024).decode()
print(recv_auth)

username = base64.b64encode('2089916453w@gmail.com'.encode()).decode() + '\r\n'
secured_socket.sendall(username.encode())
recv_user = secured_socket.recv(1024).decode()
print(recv_user)

# Send base64 encoded app password
app_password = base64.b64encode('20021126w'.encode()).decode() + '\r\n'
secured_socket.sendall(app_password.encode())
recv_pass = secured_socket.recv(1024).decode()
print(recv_pass)

# Check if the username was accepted
if recv_user.startswith('334'):
    print(Username accepted. Proceeding to password authentication.)
else:
    print(Username authentication failed. Check your username.)

# Check if the password was accepted
if recv_pass.startswith('235'):
    print(Login successful!)
else:
    print(Login failed. Check your password.)

recv = secured_socket.recv(1024).decode()
print(recv)

if recv[:3] != '220':
    print('220 reply not received from server.')

# Send HELO command and print server response.
# heloCommand = 'HELO Alice\r\n'
heloCommand = 'HELO gmail.com\r\n'
secured_socket.sendall(heloCommand.encode())
recv1 = secured_socket.recv(1024).decode()
print(recv1)

if recv1[:3] != '250':
    print('250 reply not received from server.')

# Send MAIL FROM command and print server response.
fromCommand = 'MAIL FROM: <2089916453w@gamil.com>\r\n'
secured_socket.sendall(fromCommand.encode())
recv2 = secured_socket.recv(1024).decode()
print(recv2)

# Send RCPT TO command and print server response.
rcptCommand = 'RCPT TO: <qianyouwu@qq.com>\r\n'
secured_socket.sendall(rcptCommand.encode())
recv3 = secured_socket.recv(1024).decode()
print(recv3)

# Send DATA command and print server response.
secured_socket.sendall('DATA\r\n'.encode())
recv4 = secured_socket.recv(1024).decode()
print(recv4)

# Send message data.

# file_path = data.txt
# 
# try:
#     with open(file_path, 'r') as file:
#         data = file.read()
# except FileNotFoundError:
#     print(File not found. Please check the file path.)
# except Exception as e:
#     print(An error occurred:, e)
# print(data)
# clientSocket.send(data.encode())
print(msg)
secured_socket.sendall(msg.encode())

# Message ends with a single period.
secured_socket.sendall('endmsg'.encode())
recv5 = secured_socket.recv(1024).decode()
print(recv5)

# Send QUIT command and get server response.
secured_socket.sendall('QUIT\r\n'.encode())
recv6 = secured_socket.recv(1024).decode()
print(recv6)

clientSocket.close()
secured_socket.close()

BUG

目前由于web mail都会有防止垃圾邮箱措施,所以在验证过程出现了许多的问题,本人不想使用postfix的进行搭建,所以就这样推研测试过程