使用python套接字发送消息

时间:2015-03-15 15:00:12

标签: python sockets

我正在尝试使用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

1 个答案:

答案 0 :(得分:2)

绑定到INADDR_ANY“0.0.0.0”:

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

或输入主机名而不是localhost。

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

另外,不要忘记在绑定之前启用SO_REUSEADDR:

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