Top-down computer network socket programming job Chapter

The first three online has finally made himself a bit, to be honest to think for themselves or have a lot of harvest.

Look at the last one:

Multi-threaded Web proxy server

Server: figure, multi-threaded, attention serverSocket.accept () can not be written inside the loop, because we use tcp connection is established, it is sufficient to establish a connection, write inside the loop, then the client can send a request, and then must be opened and re-establish a connection,

Socket * Import from 
Import Threading 
"" " ... forget to save 
accept http request and return information, and is capable of simultaneously receiving a plurality of requests 
" "" 
the serverPort = 12000 
serverSocket = Socket (AF_INET, SOCK_STREAM)  ServerSocket.bind (( 'localhost ' , the serverPort))  serverSocket.listen (. 5 ) DEF Connect ():. Print (threading.current_thread () getName (), "wait to receive data ..." ) connectSocket, Adress = serverSocket.accept () the while True: = connectSocket.recv Message (1024 ) .decode () Print (threading.current_thread (). getName (), "the received", adress, "data" , Message) connectSocket.send (message.upper (). encode ( )) # multithreaded operating connect function = threads [] for I in Range (. 5 ):threads.append(threading.Thread(target=
connect)) threads[i].start()

Client: you can always establish a connection to send data

* Import socket from 

ClientSocket = socket (AF_INET, SOCK_STREAM) 
ClientSocket.connect (( 'localhost', 12000 )) # Analog browser sends a request 

the while True:  fileName = the INPUT ( "resource name:" )  ClientSocket.send (fileName.encode ())  data = ClientSocket.recv (1024 ) Print ( "received data" , data.decode ()) with Open ( "response2.txt", MODE = "A +", encoding = "UTF-. 8") AS F : f.write (data.decode ())

The results are shown running, open multiple clients, can continue to transmit information:

 

 

 

 

 

 

 

 

 But there is a flaw, is that once the connection is established, it can only communicate, after the client disconnects and does not disconnect the server continues to wait for the next connection to this client, so we can take the following strategies:

1. When the client if the requested resource name plus xxx, disconnect

2. detection in the server connection is disconnected, the disconnection state is resumed accept

Change the code below, you can solve the problem: in fact, added when the input is cut, disconnected, close the client, close server-side connection with the client, so that you can form a maximum of 5 for the service, and the client can wander in and out. . .

Socket * Import from 
Import Threading 
"" " 
... forget to save 
accept http request and return information, and is capable of simultaneously receiving a plurality of requests 
" "" 
the serverPort = 12000 
serverSocket = Socket (AF_INET, SOCK_STREAM) 
ServerSocket.bind (( 'localhost ', the serverPort)) 
serverSocket.listen (. 5) 
DEF Connect (): 
    . Print (threading.current_thread () getName (), "wait to receive data ...") 
    connectSocket, Adress = serverSocket.accept () 
    the while True: 
        = connectSocket.recv Message (1024) .decode () 
        Print (. threading.current_thread () getName (), "the received", adress, "data", Message) 
        IF Message == "Cut": # disconnect ------------ 
            connectSocket.close()
            break
        connectSocket.send(message.upper().encode())

# 多线程运行connect函数
threads = []
for i in range(5):
    threads.append(threading.Thread(target=connect))
    threads[i].start()

Client

 
 
* Import socket from 

ClientSocket = socket (AF_INET, SOCK_STREAM)
ClientSocket.connect (( 'localhost', 12000)) # Analog browser sends a request

the while True:
fileName = the INPUT ( "resource name:")
ClientSocket.send (fileName.encode ())
data = ClientSocket.recv (1024)
IF fileName == "Cut": # --------- disconnected
ClientSocket.close ()
BREAK
Print ( "received data", data.decode ( ))
with Open ( "response2.txt", MODE = "A +", encoding = "UTF-. 8") AS F:
f.write (data.decode ())
 

 

Web server

Temporarily not constitute http packets sent, but simply run two programs interact

Server.py

""""
任务说明:一个简单的web服务器,有以下功能
1.使用TCP协议进行连接
2.接受http请求
3.对请求的文件进行响应
4.创建由请求的文件组成的Http响应报文
5.不存在文件则返回404
"""
from socket import *
# 创建tcp socket
tcpSocket = socket(AF_INET, SOCK_STREAM)
# 绑定地址
tcpSocket.bind(("127.0.0.1", 9999))
# 开始监听
tcpSocket.listen(5)
while True:
    print("等待连接中....")
    tcpConnect, adrr = tcpSocket.accept()
    print("接受到了来自:", adrr, "的数据")
    while True:
        try:
            data = tcpConnect.recv(1024)
            if not data:
                break
            print("接收到了数据", data)
            f = open(data, encoding="utf-8")
            result = f.read()
            # header = 'HTTP/1.1 200 OK\r\n\r\n'
            #tcpConnect.send(header.encode())
            tcpConnect.send(result.encode())
        except FileNotFoundError as e:
            tcpConnect.send("资源不存在".encode())
    tcpConnect.close()
    print("连接结束")

Client.py

from socket import *

ClientSocket = socket(AF_INET, SOCK_STREAM)
ClientSocket.connect(('localhost', 9999))     # 模拟浏览器发送请求


while True:
    fileName = input("资源名:")
    ClientSocket.send(fileName.encode())
    data = ClientSocket.recv(1024)
    print("接收到数据", data.decode())
    with open("response2.txt", mode="a+", encoding="utf-8") as f:
        f.write(data.decode())

运行结果如下,可以看到请求的文件存在时就返回文件内容,不存在就返回提示信息

Client:

 

 

Server

 UDP,PING程序:

emmmm,这个不写了,网上可以搜索到,,

邮件客户:

这个参考菜鸟教程的,

import smtplib
from email.mime.text import MIMEText
from email.header import Header

mail_host = 'smtp.qq.com'   # 中转服务器
mail_user = '[email protected]'
mail_pass = 'xzfwjkhtpsrydjdh'

sender = '[email protected]'       # 发送方
receivers = ['[email protected]']       # 接收方

message = MIMEText('python 测试', 'plain', 'utf-8')
message['From'] = Header("ennio", 'utf-8')
message['To'] = Header("测试", 'utf-8')

subject = 'python smtp 测试'
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 建立连接
    smtpObj.login(mail_user, mail_pass) # 登陆授权
    smtpObj.sendmail(sender, receivers, message.as_string())  # 发送邮件
    print("发送成功")
    smtpObj.close()
except smtplib.SMTPException:
    print("Error......")
    smtpObj.close()

 

Guess you like

Origin www.cnblogs.com/eenio/p/11494167.html
Recommended