Python:简单的客户端服务器,在第一个连接关闭后监听连接关闭

时间:2019-04-09 07:02:00

标签: python sockets server client client-server

所以我想构建简单的Server-Client

serverclients(简单的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继续侦听另一个连接。

1 个答案:

答案 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