Python-socket编程笔记

文章目录

  • HTTP\socket\TCP
  • Socket编程的模式
  • client和server实现通信
  • socket实现聊天和多用户连接
    • 实现聊天
    • 利用线程实现多用户的连接
  • socket模拟http请求

HTTP\socket\TCP

请参考网络模型,计算机给我们提供了socket,通过socket可以直接与传输层打交道

Socket编程的模式

Python-socket编程笔记_第1张图片

client和server实现通信

首先是服务端

import socket

#  指明为ipv4与tcp协议
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 必须传入元组
server.bind(("0.0.0.0", 8000))
# 实现监听
server.listen()
sock, addr = server.accept()

# 获取从客户端发送的数据,每次获取1k的数据
data = sock.recv(1024)
# 将字节流转码为utf-8编码
print(data.decode("utf-8"))
sock.close()
server.close()

接着是客户端

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 8000))
# 以字节输出
client.send("Y4tacker".encode("utf-8"))
client.close()

这样就实现了

socket实现聊天和多用户连接

实现聊天

取消close方法即可,再加个while循环

服务端
while True:
    data = sock.recv(1024).decode("utf-8")
    print(data)
    ret_data = input("输入回复:")
    sock.send(ret_data.encode("utf-8"))
客户端
while True:
    data = client.recv(1024)
    print(data.decode("utf-8"))
    ret_data = input("输入回复:")
    client.send(ret_data.encode("utf-8"))

利用线程实现多用户的连接

服务端
import socket
import threading

#  指明为ipv4与tcp协议
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).decode("utf-8")
        print(data)
        if "exit" == data:
            break
        ret_data = input()
        sock.send(ret_data.encode("utf-8"))
    sock.close()
    print("关闭连接")


while True:
    sock, addr = server.accept()
    # 用线程处理新的用户连接
    client_thread = threading.Thread(target=handle_sock, args=(sock, addr))
    client_thread.start()


客户端
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 8000))

while True:
    ret_data = input()
    client.send(ret_data.encode("utf-8"))
    data = client.recv(1024)
    print(data.decode("utf-8"))
    if "exit" == ret_data:
        print("关闭连接")
        break
client.close()


socket模拟http请求

为了方便,利用urlparse来解析url

import socket
from urllib.parse import urlparse


def get_url(url):
    url = urlparse(url)
    # 以http://www.baidu.com/aa.html为例
    # ParseResult(scheme='http', netloc='www.baidu.com', path='/aa.html', params='', query='', fragment='')
    host = url.netloc
    path = url.path
    if path == "":
        path = "/"
    # 建立socket连接
    con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # HTTP都是80端口
    con.connect((host, 80))
    # 发送请求
    con.send(f'GET {path} HTTP/1.1\r\nHost:{host}\r\nConnection:close\r\n\r\n'.encode("utf-8"))
    # 接收请求,如果数据大于1024字节,则通过多次接收
    data = b""
    while True:
        temp = con.recv(1024)
        if temp:
            data += temp
        else:
            break
    data = data.decode("utf-8")
    # 去除请求头
    html_data = data.split("\r\n\r\n")[1]
    print(html_data)
    con.close()


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

你可能感兴趣的:(#,Python高级核心技术)