所以我想构建简单的Server-Client
。
此server
从clients
(简单的string
)获得连接,完成我的工作,返回答案,关闭客户端连接并等待其他连接。
客户
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = '127.0.0.1'
port = 4500
address = (ip, port)
message = 'mymessage'
client = socket.socket()
client.connect(address)
client.sendall(message.encode('utf-8'))
服务器
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
name = socket.gethostname()
ip = '127.0.0.1'
port = 4500
address = (ip, port)
server.bind(address)
server.listen(1)
print('Start listening on', ip, ':', port)
client, addr = server.accept()
print('Received connection from', addr[0], ':', addr[1])
while True:
data = client.recv(1024).decode('utf-8')
print('Received', data, 'from the client')
# DO something.....
client.send('Goodbye'.encode('utf-8'))
client.close()
break
因此,当前client
返回server
的响应后,server
已经关闭,我希望我的server
继续侦听另一个连接。
答案 0 :(得分:0)
简单,您需要添加另一个循环,以便服务器始终可以监听:
服务器
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
name = socket.gethostname()
ip = '127.0.0.1'
port = 4500
address = (ip, port)
server.bind(address)
server.listen(1)
while True:
client, addr = server.accept()
print('Start listening on', ip, ':', port)
print('Received connection from', addr[0], ':', addr[1])
while True:
data = client.recv(1024).decode('utf-8')
print('Received', data, 'from the client')
# DO something.....
client.send('Goodbye'.encode('utf-8'))
client.close()
break