Python Socket:套接字连接被拒绝

时间:2017-05-23 09:02:52

标签: python django sockets

env:linux + python3 + rornado

当我运行client.py时,他建议我的连接被拒绝,对于几个端口,使用127.0.0.1:7233,服务器没有任何响应,但客户端提示拒绝连接,谁可以告诉我为什么?

server.py

# coding:utf8

import socket
import time
import threading


# accept conn
def get_hart(host, port):
    global clien_list
    print('begin get_hart')
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind((host, port))
    s.listen(5)
    print(clien_list)

    while True:
        try:
            clien, address = s.accept()
            try:
                clien_data = clien.recv(1024).decode('utf8')
                if clien_data == str(0):
                    clien_id = clien_reg()
                    clien.send(str(clien_id))
                    print(clien_list)
                else:
                    clien_list[int(clien_data)]['time'] = time.time()
                    # print clien_data
            except:
                print('send fail!')
            clien.close()
        except:
            print("accept fail!")
            continue


# client reg
def clien_reg():
    global clien_list
    tim = str(time.time() / 100).split('.')
    id = int(tim[1])
    clien_list[id] = {"time": time.time(), "state": 0}
    return id


# client dict
def check_hart(clien_list, delay, lost_time):
    while True:
        for id in clien_list:
            if abs(clien_list[id]['time'] - time.time()) > lost_time:
                clien_list[id]['state'] = 0
                del clien_list[id]  # del offline client
                break  # err
            else:
                clien_list[id]['state'] = 1
        print(clien_list)
        time.sleep(delay)


if __name__ == '__main__':
    host = '127.0.0.1'
    port = 7233
    global clien_list  # Dict: client info
    clien_list = {}
    lost_time = 30  # timeout
    print('begin threading')
    try:
        threading.Thread(target=get_hart,args=(host,port,),name='getHart')
        threading.Thread(target=check_hart,args=(clien_list, 5, lost_time,))
    except Exception as e:
        print("thread error!"+e)

    while 1:
        pass
    print('e')

client.py

# coding:utf8

import socket
import time


# sent pkg
def send_hart(host, port, delay):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    print(host,port)
    global clien_id
    try:
        s.connect((host, port))
        s.send(clien_id)
        if clien_id == 0:
            try:
                to_clien_id = s.recv(1024)
                clien_id = to_clien_id
            except:
                print('send fail!')
            print(to_clien_id)  # test id
        time.sleep(delay)
    except Exception as e:
        print('connect fail!:'+e)
        time.sleep(delay)


if __name__ == '__main__':
    host = '127.0.0.1'
    port = 7233
    global clien_id
    clien_id = 0  # client reg id
    while True:
        send_hart(host, port, 5)

错误

Traceback (most recent call last):
  File "/home/ubuntu/XPlan/socket_test/client.py", line 13, in send_hart
    s.connect((host, port))
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/XPlan/socket_test/client.py", line 34, in <module>
    send_hart(host, port, 5)
  File "/home/ubuntu/XPlan/socket_test/client.py", line 24, in send_hart
    print('connect fail!:'+e)
TypeError: Can't convert 'ConnectionRefusedError' object to str implicitly

Process finished with exit code 1

2 个答案:

答案 0 :(得分:0)

更改

print('connect fail!:'+e)

print('connect fail!:'+str(e))

答案 1 :(得分:0)

找到问题, 首先,线程需要start()函数来启动, 第二,Python3,send()函数接受字节的值, 第三,打印异常需要切换到str类型

threading.Thread(target=get_hart,args=(host,port,),name='getHart',).start()

print("thread error!"+str(e))