Python: 简单的客户端服务器在第一次连接关闭后监听连接关闭
Python: simple client server the listening for connections close after first connection close
所以我想构建简单的 Server-Client
。
这个 server
从 clients
获取连接(简单 string
),做我的事情,return 回答,关闭客户端连接并等待另一个连接。
客户端
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
继续监听另一个连接。
简单,需要再添加一个循环,让服务器一直监听:
服务器
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
所以我想构建简单的 Server-Client
。
这个 server
从 clients
获取连接(简单 string
),做我的事情,return 回答,关闭客户端连接并等待另一个连接。
客户端
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
继续监听另一个连接。
简单,需要再添加一个循环,让服务器一直监听:
服务器
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