1

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

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
4

1 回答 1

2

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

利用 -

c.sendto("Received", addr) 

代替

s.sendto("received", addr)

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

服务器.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()

客户端.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()
于 2016-06-20T09:57:30.287 回答