【问题标题】:Python client won't reconnect to serverPython客户端不会重新连接到服务器
【发布时间】:2012-07-13 12:10:51
【问题描述】:

我的英语很抱歉,但我的软件出现了一些问题,我需要一些帮助。但首先,一些代码!

客户端:

if connessione.connect(host, port) == True:
    connect = True
    print 'connection granted'
else:
    connect = False
    print 'connection refused'

while 1:
   do_some_stuff_with_socket

   if connect == False:
       if connessione.connect(host, port) == True:
           connect = True

服务器端:(网上找的

import socket
port = 4000
host = '127.0.0.1'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
print "Type 'Q' or 'q' to QUIT"
print "Server Waiting for client on port ", port
while 1:
    client_socket, address = server_socket.accept()
    print "Connection from ", address
    while 1:
        server_data = raw_input("--> server: ")
        if server_data.lower() == 'q':
            client_socket.send(server_data)
            client_socket.close()
            break
        else:
            client_socket.send(server_data)
        client_data = client_socket.recv(1024)
        if client_data.lower() == 'q':
            print "Quit from client"
            client_socket.close()
            break
        else:
            print "<-- client: ", client_data
    break

如果我重新启动/断开服务器连接,客户端不会重新连接。我使用了.terminate().close() 方法来关闭套接字。

【问题讨论】:

  • 断开连接是否有报错?
  • 为什么在打印“
  • @IT Ninja: 不.. 没有错误抛出... :(
  • @DevPlayer:我会尝试删除它!

标签: python sockets python-2.7 reconnect


【解决方案1】:

我通过在.connect(host, port) 之前调用.__init__() 方法解决了我的问题

它并不优雅,但它确实有效。

谢谢大家

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多