1. 程式人生 > >【python】socket程式設計簡單的例子

【python】socket程式設計簡單的例子

#socket_client.py
import socket
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(('127.0.0.1', 8000))
while True:
    re_data = input()
    client.send(re_data.encode("utf8"))
    data = client.recv(1024)
    print(data.decode("utf8"))
# client.send("bobby".encode("utf8"))
# data = client.recv(1024)
# print (data.decode("utf8")) # client.close()
#socket_server.py
import socket
import threading

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(('0.0.0.0', 8000))
server.listen()


def handle_sock(sock, addr):
    while True:
        data = sock.recv(1024)
        print(data.decode("utf8"
)) re_data = input() sock.send(re_data.encode("utf8")) #獲取從客戶端傳送的資料 #一次獲取1k的資料 while True: sock, addr = server.accept() #用執行緒去處理新接收的連線(使用者) client_thread = threading.Thread(target=handle_sock, args=(sock, addr)) client_thread.start() # data = sock.recv(1024) # print(data.decode("utf8"))
# re_data = input() # sock.send(re_data.encode("utf8")) # server.close() # sock.close()
#socket_http.py

#requests -> urlib -> socket
import socket
from urllib.parse import urlparse


def get_url(url):
    #通過socket請求html
    url = urlparse(url)
    host = url.netloc
    path = url.path
    if path == "":
        path = "/"

    #建立socket連線
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # client.setblocking(False)
    client.connect((host, 80)) #阻塞不會消耗cpu

    #不停的詢問連線是否建立好, 需要while迴圈不停的去檢查狀態
    #做計算任務或者再次發起其他的連線請求

    client.send("GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n".format(path, host).encode("utf8"))

    data = b""
    while True:
        d = client.recv(1024)
        if d:
            data += d
        else:
            break

    data = data.decode("utf8")
    html_data = data.split("\r\n\r\n")[1]
    print(html_data)
    client.close()

if __name__ == "__main__":
    import time
    start_time = time.time()
    for url in range(20):
        url = "http://shop.projectsedu.com/goods/{}/".format(url)
        get_url(url)
    print(time.time()-start_time)