我正在尝试使用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()
代码有什么问题?我一直在搜索谷歌,这个网站和其他几个,但似乎无法找到任何东西。当我尝试解决方案他们只是不工作... 谢谢你的帮助。
答案 0 :(得分:1)
host
需要是本地地址
bind(...) method of socket._socketobject instance bind(address) Bind the socket to a local address. For IP sockets, the address is a pair (host, port); the host must refer to the local host. For raw packet sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
你的意思是s.connect
吗?