python socket编程 tcp 简单示例

时间:2022-12-14 22:29:58

SOCKET基础编程


功能说明

  • python版本3.5.1
  • 客户端连接服务器,server发送欢迎词并询问用户姓名,收到client回复,向client发送‘hello,***
  • client向server发送数据,server打印收到的数据
  • 用线程处理多客户端连接

Client

  • demo_socket_client.py
import socket

# client
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #AF_INET(IPV4使用) SOCK_STREAM(TCP模式)

client.connect(('localhost', 8080)) #连接本地回环地址127.0.0.1 端口号8080 以元组作为参数

print(client.recv(1024).decode('utf-8'))

while True:
sendbuf = input() # 输入
client.send(sendbuf.encode('utf-8')) # UTF-8编码
if not sendbuf or sendbuf == 'exit': #退出条件判断
break
recvbuf = client.recv(1024)
print(recvbuf.decode('utf-8')) # 解码
client.close() # 断开连接
print('Connection was closed...')

客户端运行截图

python socket编程  tcp 简单示例


Server

  • demo_socket_server.py
import socket
import threading
import time

ser = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

ser.bind(('127.0.0.1', 8080))

ser.listen(5) # 监听连接 如果有超过5个连接请求,从第6个开始不会被accept

print('Server is running...') # 打印运行提示

def tcplink(connect, addr):
print('Accept new connection from %s:%s...' % addr)
connect.send(b'Welcome!\r\n'+b'Please tell me your name:')
data = connect.recv(1024)
connect.send(('Hello, %s' % data.decode('utf-8')).encode('utf-8'))
while True:
data = connect.recv(1024)
time.sleep(1)
if not data or data.decode('utf-8') == 'exit':
break
print("Device: %s, Data: %s, Size: %s" % (addr[0], data.decode('utf-8'), len(data)))
connect.send(b'Data Receive')
connect.close()
print('Connection from %s:%s closed' % addr)

while True:
sock, addr = ser.accept()
pthread = threading.Thread(target=tcplink, args=(sock, addr)) #多线程处理socket连接
pthread.start()

服务器运行截图

python socket编程  tcp 简单示例