套接字 - 简单服务器/客户端 - socket.error:[Errno 10060]

时间:2016-08-07 19:32:28

标签: python sockets

我在端口9999上运行了一个非常简单的套接字服务器代码。当我启动我的服务器和客户端时,使用netstat,我可以看到服务器正在运行,客户端位于短暂的7180端口。

TCP    192.168.1.117:9999     0.0.0.0:0              LISTENING       7180

但是,客户端的输出显示以下错误:

Traceback (most recent call last):
  File "client.py", line 6, in <module>
    clisock.connect((host, 9999))
  File "C:\Python27\lib\socket.py", line 222, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

我的服务器代码:

import socket
import sys
import time

srvsock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
print 'Server Socket is Created'

host = socket.gethostname()
try:
    srvsock.bind( (host, 9999) )
except socket.error ,  msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

srvsock.listen(5)
print 'Socket is now listening'

while True:
    clisock, (remhost, remport) = srvsock.accept()
    print 'Connected with ' + remhost + ':' + str(remport)
    currentTime = time.ctime(time.time()) + "\r\n"
    print currentTime
    clisock.send(currentTime)

clisock.close()
srvsock.close()

我的Socket客户端程序如下:

import socket
clisock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)

host = socket.gethostname()
print host
clisock.connect((host, 9999))


tm = clisock.recv(1024)

clisock.close()

print tm

问题是什么?它可能是防火墙或导致连接断开的东西吗?

1 个答案:

答案 0 :(得分:1)

无法保证socket.gethostname()将返回FQDN。尝试将服务器绑定到''(空字符串是符号名称,表示所有可用接口),然后将客户端连接到localhost127.0.0.1

Python文档包含一个非常有用的示例,用于使用低级套接字API [1]创建简单的TCP服务器 - 客户端应用程序。

[1] https://docs.python.org/2/library/socket.html#example