zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【Python】Server/Client 通信 服务端/客户端

Pythonserver客户端通信 Client 服务端
2023-09-11 14:16:50 时间

1、效果

 

 

 

 

 

 

2、代码

2.1、服务端

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Time    :2022/1/27 10:15
@Author  :
@File    :server.py
@Version :1.0
@Function:
"""
import socket

# 创建一个socket
s = socket.socket()

# 服务器基本信息
host = socket.gethostname()
port = 8643

# socket绑定服务器
s.bind((host, port))

# 监听
s.listen(5)

while True:
    c, addr = s.accept()
    print("got connection from", addr)
    data = '连接成功'
    c.send(data.encode())
    print(f'服务端接收:{c.recv(1024).decode()}')
    c.close()

 

2.2、客户端

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Time    :2022/1/27 10:15
@Author  :
@File    :client.py
@Version :1.0
@Function:
"""
import socket

# 创建一个socket
s = socket.socket()

# 服务器基本信息
host = socket.gethostname() # 修改为服务器IP
port = 8643

# 连接服务器
s.connect((host, port))

# 接收服务器发送的消息
print(f'接收:{s.recv(1024).decode()}')

# 向服务器发送消息
s.send(bytes('客户端发送消息', encoding='utf-8'))