【问题标题】:python socket tcp server refuse connectionpython socket tcp服务器拒绝连接
【发布时间】:2015-05-07 06:04:58
【问题描述】:

您好,我尝试使用 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

【问题讨论】:

  • 您的服务器丢失bind()
  • 如果您有解决方案,您可以在提供的答案框中写下它,然后接受它。这比将“已解决”一词编辑到问题中更可取。

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


【解决方案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()

【讨论】:

    猜你喜欢
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2014-01-10
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多