gpt4 book ai didi

Python 套接字连接无法正常工作

转载 作者:可可西里 更新时间:2023-11-01 02:43:00 24 4
gpt4 key购买 nike

下面是我目前使用的代码:

soc1 = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ADDR = (HOST,PORT)
soc1.connect(ADDR)
soc1.send('WILL SEND')

运行上述代码时收到的错误消息是:

Traceback (most recent call last):
File "C:\workspace\wx_python_test\chat_server.py", line 25, in <module>
soc1.connect(ADDR)
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10061]

谁能解释一下我遇到的问题是什么以及我该如何纠正它?

完整源代码:http://pastie.org/4245314

最佳答案

socket.error: [Errno 10061] 表示您尝试连接的端口未打开。您需要确保端口已打开并且正在监听您要建立的连接。

看来您正在尝试测试聊天服务器。为了让聊天服务器正常工作,您需要确保它当前正在监听指定端口。

Twisted如果您之前没有检查过,它提供了一个很好的框架。

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):

def __init__(self, users):
self.users = users
self.name = None
self.state = "GETNAME"

def connectionMade(self):
self.sendLine("What's your name?")

def connectionLost(self, reason):
if self.users.has_key(self.name):
del self.users[self.name]

def lineReceived(self, line):
if self.state == "GETNAME":
self.handle_GETNAME(line)
else:
self.handle_CHAT(line)

def handle_GETNAME(self, name):
if self.users.has_key(name):
self.sendLine("Name taken, please choose another.")
return
self.sendLine("Welcome, %s!" % (name,))
self.name = name
self.users[name] = self
self.state = "CHAT"

def handle_CHAT(self, message):
message = "<%s> %s" % (self.name, message)
for name, protocol in self.users.iteritems():
if ':' in message:
self.exc(message.split(':')[0])
if protocol != self:
protocol.sendLine(message)

def exc(self, cmd):
print cmd
if cmd == 'who':
for i in self.users:
print i


class ChatFactory(Factory):

def __init__(self):
self.users = {} # maps user names to Chat instances

def buildProtocol(self, addr):
return Chat(self.users)


reactor.listenTCP(8123, ChatFactory())
reactor.run()

关于Python 套接字连接无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11458088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com