最基础的python socket demo

基础部分

server

import socket


def socket_server():
    HOST = '0.0.0.0'
    PORT = 5001
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 定义socket类型,网络通信,TCP
    s.bind((HOST, PORT))
    s.listen(1)  # 开始TCP监听,监听1个请求
    print("listening ... ")
    while 1:
        conn, addr = s.accept()  # 接受TCP连接,并返回新的套接字与IP地址
        print('Connected by', addr)  # 输出客户端的IP地址
        conn.send(bytes("Connected success", encoding='utf-8'))
        while 1:
            data = str(conn.recv(1024), encoding='utf-8')  # 把接收的数据实例化
            # conn.send(bytes("has recv data: " + data, encoding='utf-8'))
            print(data)
    conn.close()  # 关闭连接


if __name__ == "__main__":
    socket_server()

client

import socket


def socket_client():
    HOST = '127.0.0.1'
    PORT = 5001
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 定义socket类型,网络通信,TCP
    s.connect((HOST, PORT))
    data = s.recv(1024)  # 把接收的数据实例化
    print(data)
    while 1:
        cmd = input("Please input cmd:")  # 与人交互,输入命令
        s.send(bytes(cmd, encoding='utf-8'))  # 把命令发送给对端
        # data = s.recv(1024)  # 把接收的数据定义为变量
    s.close()  # 关闭连接


if __name__ == "__main__":
    socket_client()

Python实现一个服务端,多个客户端接入

服务器端

服务器端每一次接收客户端连接,都要fork一个进程来完成,如果单纯使用socket模块来实现,是不容易完成多线程接入的。为了方便,可以直接使用socketserver 模块。

from socketserver import BaseRequestHandler, ThreadingTCPServer


class Handler(BaseRequestHandler):

    def handle(self) -> None:
        address, pid = self.client_address
        print(f'{address} connected!')
        while True:
            data = self.request.recv(1024)
            if len(data) <= 0:
                print("close!")
                break
            print(f'receive data: {data.decode()}')
            self.request.sendall('response'.encode())


if __name__ == '__main__':
    server = ThreadingTCPServer(('127.0.0.1', 8998), Handler)
    print("Listening")
    server.serve_forever()

客户端代码

import socket


class Client:
    def __init__(self):
        # ipv4  TCP
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def connect(self, server_ip, server_port):
        self.client.connect((server_ip, server_port))

    def run(self):
        while True:
            print("please input:")
            message = input()
            self.client.sendall(message.encode())
            response = self.client.recv(1024)
            print(response.decode())


if __name__ == '__main__':
    client = Client()
    client.connect('127.0.0.1', 8998)
    client.run()
posted @ 2022-08-04 16:49  bitterteaer  阅读(172)  评论(0编辑  收藏  举报