[socket] Python socket使用 - 百年刘傲天

in Pythonsocket with 0 comment

代码如下

服务端

#!/usr/bin/env python3
# coding=utf-8

import socket
import threading

bind_ip = "127.0.0.1"
bind_port = 9999

# 创建套接字
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定ip和端口
server.bind((bind_ip, bind_port))
# 最大连接数5
server.listen(5)

print("[*] Listing on {}:{}".format(bind_ip, bind_port))
def handle_client(client_socket):
    """
    处理客户端连接
    """
        # 接收消息
    request = client_socket.recv(1024)

    print("[*] Received: {}".format(request))

    # 接收消息成功,返回一个收到
    client_socket.send(bytes("收到!", encoding="UTF-8"))
    client_socket.close()
while True:
    # 监听端口,等待连接
    client, addr = server.accept()

    print("[*] Acceptd connection from: {}:{}".format(addr[0], addr[1]))

    # 将已连接的套接字放入子线程处理 这样不会影响主线程
    client_header = threading.Thread(target=handle_client, args=(client,))
    client_header.start()

客户端

#!/usr/bin/env python3
# coding=utf-8

import socket
    # 连接的IP
target_host = "127.0.0.1"
    # 连接的端口
target_port = 9999

# 创建套接字
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务端
client.connect((target_host, target_port))
# 发送数据 需要转化为二进制
client.send(bytes("GET / HTTP/1.1\r\nHost: www.allsrc.cn\r\n\r\n",
              encoding="UTF-8"))
# 接受数据
response = client.recv(4096)
    # 打印回显
print(str(response, encoding="UTF-8"))
Responses