发布网友 发布时间:2022-04-29 01:37
共1个回答
热心网友 时间:2022-04-18 06:33
一个简单的CS通信的例子(只实现功能,没有考虑异常处理、断开连接等问题):
# server.py# client.py
import socket, threading
def send(socket):
while True:
sendmsg = input()
socket.send(sendmsg.encode())
def receive(socket):
while True:
b = socket.recv(1024)
msg = b.decode()
print('来自服务器的消息:%s' % msg)
try:
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('尝试连接服务器...')
sk.connect(('127.0.0.1',9999))
print('已连接到服务器。说点什么吧!')
tsend = threading.Thread(target=send, args=(sk,))
trecv = threading.Thread(target=receive, args=(sk,))
tsend.start()
trecv.start()
tsend.join()
trecv.join()
except socket.error as e:
print('无法连接到服务器:%s' % e)