python socket tcp server拒绝连接

时间:2015-03-05 18:31:55

标签: python sockets tcp network-programming python-sockets

您好我尝试使用python套接字连接客户端和服务器... 双方(客户端和服务器)正在运行,没有任何错误...... 问题:当我尝试将客户端连接到服务器时,它会出现以下错误。

Traceback (most recent call last):
  File "tcpclient.py", line 8, in <module>
    client.connect((hos,po))
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused

我尝试使用netcat监听端口......而且它有效 这是我的代码

服务器:

mport socket
import threading

ip = "0.0.0.0"
po = 9999

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server.listen(5)

print "[*] Listining on %s:%d" %(ip,po)

def handle_client(client_socket):
        request = client_socket.recv(1024)
        print "[*] Received: %s" % request
        client_socket.close()

while True :
        client,addr = server.accept()
        print "[*] Accepted connection from %s:%d" %(addr[0],addr[1])
        client_handler = threading.Thread(target=handle_client,args=(client,))
        client_handler.start()

客户:

import socket

hos =  "127.0.0.1"
po = 9999

client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

client.connect((hos,po))

client.send("Hello")

re = client.recv(3456)
print re

1 个答案:

答案 0 :(得分:1)

代码应该是这样的:

import socket
import threading

ip = "0.0.0.0"
po = 9999

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((ip,po))# This line was missing :p thanks
server.listen(5)

print "[*] Listining on %s:%d" %(ip,po)

def handle_client(client_socket):
        request = client_socket.recv(1024)
        print "[*] Received: %s" % request
        client_socket.close()

while True :
        client,addr = server.accept()
        print "[*] Accepted connection from %s:%d" %(addr[0],addr[1])
        client_handler = threading.Thread(target=handle_client,args=(client,))
        client_handler.start()