【问题标题】:Python Socket [Errno 10049] 'The requested address is not valid in its context'Python Socket [Errno 10049] '请求的地址在其上下文中无效'
【发布时间】:2014-11-18 22:56:58
【问题描述】:

我正在尝试让 python 套接字代码工作。服务器运行良好,但客户端不会绑定到 IP 地址。这是错误:

Traceback (most recent call last):
  File "chatClient.py", line 27, in <module>
    s.bind((host, port))
  File "C:\Panda3D-1.8.1\python\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context
Press any key to continue . . .

这是代码...

import socket
import threading
import os
import time

tLock = threading.Lock()
shutdown = False

def receving(name, sock):
    while not shutdown:
        try:
            tLock.acquire()
            while True:
                data, addr = sock.recvfrom(1024)
                print str(data)
        except:
            pass
        finally:
            tLock.release()

host = '76.106.199.228'
port = 0

server = ('76.106.199.228', 5000)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)

rT = threading.Thread(target=receving, args=("RecvThread",s))
rT.start()

alias = raw_input("Name: ")
message = raw_input(alias + ": ")
while message != 'q':
    if message != '':    
        s.sendto(alias + ": " + message, server)
    tLock.acquire()
    message = raw_input(alias + ": ")
    tLock.release()
    time.sleep(0.2)

shudown = True
rT.join()
s.close()

代码有什么问题?我一直在谷歌、这个网站和其他一些网站上搜索,但似乎找不到任何东西。当我尝试解决方案时,它们只是不起作用... 感谢您的帮助。

【问题讨论】:

    标签: python sockets


    【解决方案1】:

    host 需要是本地地址

    socket._socketobject 实例的 bind(...) 方法 绑定(地址) 将套接字绑定到本地地址。对于 IP 套接字,地址是 对(主机,端口);主机必须引用本地主机。对于原始数据包 套接字地址是一个元组(ifname, proto [,pkttype [,hatype]])

    你的意思是s.connect吗?

    【讨论】:

    • 我尝试了 s.connect,但由于某种原因它不会将消息发送到服务器。有什么方法可以绑定它或做一些类似于绑定但到外部地址的事情?
    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多