为什么此服务器程序无法向客户端发送任何内容?

时间:2016-06-20 09:24:10

标签: python python-2.7 sockets python-sockets

我基本上是想创建一个聊天应用程序,但在这里我无法从服务器向客户端发送任何内容。我该如何纠正? 服务器程序:

from socket import *
host=gethostname()
port=7777
s=socket()
s.bind((host, port))
s.listen(5)
print "Server is Ready!"
while True:
    c, addr= s.accept()
    print c
    print addr
    while True:
        print c.recv(1024)
        s.sendto("Received",addr)
s.close()

客户端程序:

from socket import *
host=gethostname()
port=7777
s=socket()
s.connect((host, port))

while True:
    s.send(( raw_input()))
    prin s.recv(1024)

s.close()

在服务器程序中s.sendto给出错误:

File "rserver.py", line 14, in <module>
    s.sendto("Received",addr)
socket.error: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

1 个答案:

答案 0 :(得分:2)

您不能使用连接套接字来发送或接收对象,因此问题只有....

使用 -

c.sendto("Received", addr) 

而不是

s.sendto("received", addr)

第二个问题是你没有收到来自套接字的消息......这是工作代码

server.py -

from socket import *
host=gethostname()
port=7777
s=socket()
s.bind((host, port))
s.listen(5)
print "Server is Ready!"
while True:
    c, addr= s.accept()
    print c
    print addr
    while True:
        print c.recv(1024)
        #using the client socket and make sure its inside the loop
        c.sendto("Received", addr)    
s.close()

client.py

from socket import *
host=gethostname()
port=7777
s=socket()
s.connect((host, port))

while True:
    s.send(( raw_input()))
    #receive the data
    data = s.recv(1024)
    if data:
         print data
s.close()