简体   繁体   中英

Python sockets not sending data immediately

I am making a game in python. It uses sockets. It is my first time using sockets.

Here is part of my code:

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# get local machine name
host = socket.gethostname()                           

port = 9999                                           

# bind to the port
serversocket.bind((host, port))                                  

# queue up to 5 requests
serversocket.listen(5)                                       

player = 1
keys = []
playerSockets = []
print "Waiting for players..."
while True:
    # establish a connection
    clientsocket, addr = serversocket.accept()

    key = id_generator()
    keys.append(key)

    playerSockets.append(clientsocket)
    clientsocket.send(str(player)+"\r\n")
    clientsocket.send(str(key)+"\r\n")
    print "Player " + str(player) + " connected." 
    player = player + 1

    if player > 3 or currentEpochtime() > endConn:
        break

print str(player-1) + " active players.\n"

if(player < 3):
    print "Not enough Players. Closing..."
    serversocket.close()
    quit()


#Other Stuff Continues

Now, it only sends the above data (player and key) only after the next send statement comes in my code. But then, that next send statement never sends because it is waiting for a reply from the client. But the client is not sending anything as it still hasn't received the data from the previous send statement in the server.

I have been trying to find a solution for a very long time, but cannot do so.

Please help!

Not quite sure about your question, do you mean client couldn't receive info from server?

I try with the following client code:

import socket

s = socket.socket()
host = socket.gethostname()
port = 9999
s.connect((host, port))
print s.recv(1024)
input = raw_input('type anything and click enter... ')
s.send(input)
print "the message has been sent"

It seems to receive data sent by server and be able to send data back to server.

Does this help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM