Skip to main content
 首页 » 编程设计

python之使用 python 套接字发送消息

2024年10月25日7txw1958

我正在尝试使用 python 套接字建立通信链接并发送另一端(服务器)接收的消息,我总是遇到同样的问题 这是代码

客户端代码:

import socket 
s = socket.socket()  
host = raw_input("Enter a Hostname : ") 
port = input ("Enter a port to communicate on : ") 
message = raw_input("What do you want to send (Up , Down , Left , Right) : ") 
 
s.connect((host,port)) 
while True : 
if message == "Up" or "up" : 
    M = 'U' 
elif message == "Down" or "down" : 
    M = 'D' 
elif message == "Left" or "left" : 
    M = 'L' 
elif message == "Right" or "right" : 
    M = 'R' 
else : 
    print ("Please Enter a Valued Word : ") 
    M = '0' 
    s.send(M) 
    print ("This is the sent messages %s to IP %s", (M , host)) 
print (s.recev(1024)) 
s.close 

服务器代码:

import socket  
 
s = socket.socket()        
host = socket.gethostname()  
port = 8080               
s.bind((host, port))  
 
s.listen(5)                 
while True: 
   c, addr = s.accept()      
   print 'Got connection from', addr 
   c.send('Connected') 
   c.close()                 

我总是得到以下错误

Traceback (most recent call last): 
  File "third_att.py", line 9, in <module> 
    s.connect((host,port)) 
  File "C:\Python27\lib\socket.py", line 224, in meth 
    return getattr(self._sock,name)(*args) 
socket.error: [Errno 10060] A connection attempt failed because the connected pa 
rty did not properly respond after a period of time, or established connection f 
ailed because connected host has failed to respond 

请您参考如下方法:

绑定(bind)到 INADDR_ANY“0.0.0.0”:

s.bind(("0.0.0.0", port)) 

或输入主机名而不是本地主机。

尝试在'bind()'之前在服务器上打印主机名。

此外,不要忘记在绑定(bind)之前启用 SO_REUSEADDR:

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)