socket编程 python示例(C/S模式, TCP)

server

import socket
from threading import Thread
 
# 主机地址为空字符串,表示绑定本机所有网络接口ip地址
IP = ''
# 端口号
PORT = 50000
# 定义一次从socket缓冲区最多读入512个字节数据
BUFFER = 512
 
 
def process_socket(s: socket.socket, address):
    print(f"与{address}的连接建立")
    with s:
        while True:
            try:
                received = s.recv(BUFFER)
 
                if not received:
                    print(f'与{address}的连接断开')
                    break
 
                # 读取的字节数据是bytes类型,需要解码为字符串
                info = received.decode()
 
                print(f'收到对方信息: {info}')
            except ConnectionResetError:
                print(f"{address}强制断开连接")
                return
 
            # 发送的数据类型必须是bytes,所以要编码
            c.send(f'服务端接收到了信息 {info}'.encode())
 
 
if __name__ == '__main__':
    # 实例化一个socket对象
    # 参数 AF_INET 表示该socket网络层使用IP协议
    # 参数 SOCK_STREAM 表示该socket传输层使用TCP协议
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as welcomeSocket:
 
        # socket绑定地址和端口
        welcomeSocket.bind((IP, PORT))
 
        # 使socket处于监听状态,等待客户端的连接请求
        # 参数 8 表示 最多接受多少个等待连接的客户端
        welcomeSocket.listen(8)
        print(f'服务端启动成功,在{PORT}端口等待客户端连接...')
 
        while True:
            c, addr = welcomeSocket.accept()
            print('接受一个客户端连接:', addr)
            # 用多线程的方式解决server同时只能为一个client服务的问题
            t = Thread(target=process_socket, args=(c, addr))
            t.start()
 

client

from socket import *
 
IP = '127.0.0.1'
PORT = 50000
BUFFER = 1024
 
if __name__ == '__main__':
 
    # 实例化一个socket对象,指明协议
    with socket(AF_INET, SOCK_STREAM) as dataSocket:
 
        # 连接服务端socket
        try:
            dataSocket.connect((IP, PORT))
        except ConnectionRefusedError:
            print('服务器拒绝连接')
            exit(0)
 
        while True:
            # 从终端读入用户输入的字符串
            toSend = input('>>> ')
            if toSend == 'exit':
                break
            # 发送消息,也要编码为 bytes
            dataSocket.send(toSend.encode())
 
            # 等待接收服务端的消息
            received = dataSocket.recv(BUFFER)
            # 如果返回空bytes,表示对方关闭了连接
            if not received:
                break
            # 打印读取的信息
            print(received.decode())
 

python中socket常用方法

  • bind: 绑定端口
  • listen: 监听端口
  • recev: 接受信息
  • accept: 接受一个连接请求(在此之前有listen)
  • send: 发送信息
  • connect: 请求连接
  • close: 关闭socket(python中通常用with管理socket)