Python keeping socket alive?

别等时光非礼了梦想. 提交于 2020-01-03 05:41:11

问题


Hey I'm working on a python project using sockets. Basically I want to loop a connection to a host for user input. Here is what I'm trying:


while True:
    sock.connect((host, port))
    inputstring = " > "
    userInput = raw_input(inputstring)
    sock.send(userInput + '\r\n\r\n')
    recvdata = sock.recv(socksize)
    print(recvdata)

But when I loop the socket and try connecting to localhost on port 80 I get an error saying the transport endpoint is still connected or something like that. How can I eliminate that problem?


回答1:


Call connect outside the while loop. You only need to connect once.




回答2:


Put the sock.connect outside of your while True.




回答3:


You only need to connect to the host once, then you can run your loop. Try:

sock.connect((host, port))
while True:
    inputstring = " > "
    # etc

If the body of your loop were to sock.close(), you would need to .connect() again at the top of the loop. But you probably don't want to disconnect and reconnect each time, so do the above.



来源:https://stackoverflow.com/questions/5201388/python-keeping-socket-alive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!