python之socket编程

import socket
import threading
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(('127.0.0.1',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'))

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.format(data).encode("utf8"))
    # server.close()
    # sock.close()
# 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.close()
# socket_http
# request-> urllib->socket
import socket
from urllib.parse import urlparse
def get_url(url):
    url = urlparse(url)
    host = url.netloc
    path = url.path
    if path == "":
        path = "/"
    client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    client.connect((host,80))
    # print(path,host)
    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_dat = data.split("\r\n\r\n")[-1]
    print(html_dat)
    client.close()

if __name__=="__main__":
    get_url("http://www.baidu.com")


©️2020 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值