在 Python 中,客户端和服务器是否可以同时在同一个程序中运行。我想将客户端连接到外部服务器和服务器以同时从该外部服务器接收消息。每当我的服务器从该外部服务器接收到消息时,我的客户端应相应地向该外部服务器发送消息。
以下是我试图实现的方式(只是连接部分)
import select
import socket
host = 'localhost'
portClient = 6000
portServer = 7000
backlog = 5
size = 1024
client = socket.socket()
server = socket.socket()
client.connect((host,portClient))
client.send('#JOIN')
server.bind((host,portServer))
server.listen(backlog)
running = 1
while running:
c,address = server.accept()
c.close()
client.close()
server.close()
当我运行此代码时,外部服务器没有响应。当 while 循环被省略时。我收到一条错误消息,说我们的服务器已主动拒绝接受外部服务器。
我可以通过使用 Python 选择模块或线程模块来实现这一点吗?或者,还有更好的方法?