一个简单的CS通信的例子(只实现功能,没有考虑异常处理、断开连接等问题):
# server.py
import socket, threading
def send(socket):
while True:
sendmsg = input()
socket.send(sendmsg.encode())
def receive(socket, addr):
while True:
b = socket.recv(1024)
msg = b.decode()
print('来自客户端%s:%d的消息:%s' % (addr[0],addr[1],msg))
try:
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.bind(('127.0.0.1',9999))
sk.listen(1)
print('服务器已启动,最多允许1个连接')
sk_client, addr = sk.accept()
print(type(addr))
print('来自%s:%d的新连接!说点什么吧:' % (addr[0], addr[1]))
tsend = threading.Thread(target=send, args=(sk_client,))
trecv = threading.Thread(target=receive, args=(sk_client,addr))
tsend.start()
trecv.start()
tsend.join()
trecv.join()
except socket.error as e:
print('与客户端的连接出错:%s ' % e)# 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)