Python套接字服务器 - 继续接收客户端数据

时间:2014-05-10 01:24:14

标签: python sockets

如果有连接,我怎么能有一个Python套接字服务器告诉我,然后CONTINUE给我回送客户端发送的数据?当我这样做时,它连接然后只是循环,告诉我它一遍又一遍地连接。

我只想让它连接,然后不断检查(或抓取)发送到服务器的数据。

另外,如何判断客户端是否已断开连接?

address = ('', 7777)
server_socket = socket(AF_INET, SOCK_STREAM)
server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
try:
    server_socket.bind(address)
except Exception, e:
    print colored("Address already in use", 'red')

server_socket.listen(2)

print colored("Socket ready", 'blue')
while True:
    client_socket, addr = server_socket.accept()
    hostIP = addr[0]
    port = addr[1]

    try:
        host = gethostbyaddr(hostIP)[0]
    except:
        host = hostIP
    print colored("Got connection from: " + host, 'blue')
    try:
        recv_data = server_socket.recv(2048)
        print("Got: " + recv_data)
    except:
        print "nothing"
        recv_data = "" # this is because I test what it is later, but that's irrevlevant.

由于

1 个答案:

答案 0 :(得分:0)

你没有对client_socket做任何事情;即:实际的客户端连接。此外,服务器 不知道客户想要发送多少,所以它必须 CONTINUE (即:在a loop)接收数据。当连接发送“空”时数据,连接 终止,服务器返回监听。如果你想要服务器 接受新连接并继续从现有连接接收数据 查找threading模块。

import socket

address = ('', 7777)
server_socket = socket.socket(AF_INET, SOCK_STREAM)
server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
try:
    server_socket.bind(address)
except Exception, e:
    print colored("Address already in use", 'red')

server_socket.listen(2)

print colored("Socket ready", 'blue')
while True:
    client_socket, addr = server_socket.accept()
    hostIP = addr[0]
    port = addr[1]

    try:
        host = gethostbyaddr(hostIP)[0]
    except:
        host = hostIP
    print colored("Got connection from: " + host, 'blue')
    while True:
        try:
            recv_data = client_socket.recv(2048)
            if not recv_data:
                break
            print("Got: " + recv_data)
        except socket.error, e:
            print "nothing"
            recv_data = "" # this is because I test what it is later, but that's irrevlevant.