Question

How can I have a Python socket server tell me when there is a connection and then CONTINUE to give me back data that the client sends? When I do it, it connects and then just loops over, telling me it connected over and over again.

I,just want it to connect and then continually check (or grab) data sent to the server.

Also, how can I tell if the client disconnected?

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.

Thanks

Was it helpful?

Solution

You didn't do anything with client_socket; ie: the actual client connection. Furthermore, the server cannot know how much the client wants to send and so it must CONTINUE (ie: in a loop) to receive data. When the connection sends 'empty' data, the connection is terminated and the server goes back to listening. If you want the server to accept new connections and continue to receive data from existing connections look up the threading module.

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top