python tcp客户端与服务端通信

2022-10-31 09:40:48 浏览数 (1)

客户端与服务端通过socket进行通信。

服务端:

代码语言:javascript复制
import socket
import threading

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#监听0.0.0.0这个特殊的ip,就可以监听本机上所有的ip地址
sock.bind(('0.0.0.0', 10086))
sock.listen(5)#限制最多同时连接的客户端数量为5


def echo_server(client: socket.socket, address: tuple):
    print('来自{}:{}的客户端已连接'.format(address[0], address[1]))
    client.send('欢迎来自{}:{}的新客户端rn'.format(address[0], address[1]).encode('utf-8'))
    while True:
        content = client.recv(1024)
        if content == b'exit':
            break
        elif content:
            print(content.decode('utf-8'))
        else:
            break
    print('来自{}:{}的客户端已退出'.format(address[0], address[1]))
    client.close()

print('Server start! Listening 0.0.0.0:10086')
while True:
    client, address = sock.accept()
    t = threading.Thread(target=echo_server, args=(client, address))
    t.start()

客户端

代码语言:javascript复制
import socket


client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 10086))
client.send("I'm Client!".encode('utf-8'))

server_content = client.recv(1024)
print(server_content.decode('utf-8'))
client.send(b'exit')
client.close()

当客户端连接的时候,服务端输出:

代码语言:javascript复制
Server start! Listening 0.0.0.0:10086
来自127.0.0.1:64219的客户端已连接
I'm Client!
来自127.0.0.1:64219的客户端已退出

客户端:

代码语言:javascript复制
欢迎来自127.0.0.1:64219的新客户端

0 人点赞