【问题标题】:Why is this server program not able to send anything to the client?为什么此服务器程序无法向客户端发送任何内容?
【发布时间】:2016-06-20 09:24:10
【问题描述】:

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

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

【问题讨论】:

  • 您是否尝试使用通过接受返回的套接字?把 s.sendto("Received", addr) 改成 c.send("Received")。
  • 也不行。

标签: python python-2.7 sockets python-sockets


【解决方案1】:

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

使用 -

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()

【讨论】:

  • 文件“rserver.py”,第 20 行,在 s.send("Received") socket.error: [Errno 10057] 不允许发送或接收数据的请求,因为套接字未连接并且(使用 sendto 调用在数据报套接字上发送时)没有提供地址
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2018-10-19
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多