服务器停止显示消息,但在客户端关闭时发送垃圾邮件

时间:2015-09-11 16:51:27

标签: python client-server

我在Python中创建了一个简单的客户端 - 服务器应用程序,但是在客户端发出3条消息之后,服务器才停止显示它们。当客户端关闭连接时,服务器会发送空输入。谁能告诉我为什么?

Server.py

import socket
import threading

bind_ip = "127.0.0.1"
bind_port = 4443

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(10)

print "[*] Listening on %s:%d" % (bind_ip, bind_port)

# Ths is our thread for handling clients
def handle_client(client_socket, address):
    running = True
    while running:
        # Print out what the client sends to us.
        request = client_socket.recv(1024)
        print "[*] Data received from %s: %s " % (address[0], request)

        if request == 'shutdown':
            running = False

    client_socket.send("Closing server. Bye.")
    client_socket.close()
    print 'Server not available for new connections.'

while True:
    client, addr = server.accept()
    print '[*] Accepted incoming connection from: %s:%d' %  
    (addr[0],addr[1])
    client.send("You're now connected! Enjoy.")

    # Spin up our client thread to handle incoming data
    client_handler = threading.Thread(target=handle_client, args=(client, 
    addr))
client_handler.start()

Client.py

import socket

target_host = "127.0.0.1"
target_port = 4443

# Create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the client
client.connect((target_host, target_port))

while True:
    # Read some input from the keyboard
    msg = raw_input()

    client.send(msg)

    # Receive some data
    response = client.recv(1024)

    print response

1 个答案:

答案 0 :(得分:0)

客户端冻结,因为服务器只响应一次数据:"You're now connected! Enjoy."

阻止了
# Receive some data
response = client.recv(1024)

您可以通过在单独的线程中打印服务器响应来解决此问题:

import socket

target_host = "127.0.0.1"
target_port = 4443

# Create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the client
client.connect((target_host, target_port))


def handle_server(client):
    while True:
        print(client.recv(1024))

while True:
    # Read some input from the keyboard
    msg = input('Input:')

    client.send(msg)

    # Receive some data
    import threading
    server_handler = threading.Thread(target=handle_server, args=(client,))
    server_handler.start()