简体   繁体   中英

Python socket.send not working

Simple client - server app.

#Server use decode
import socket


s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host,port))

s.listen(5)

while True:

    c,addr = s.accept()
    print("Got connection from " + str(addr))
    ret_val = s.send("Thank you".encode('utf-8'))
    print ("ret_val={}".format(ret_val))
    c.close()

Client:

#client use decode
from socket import gethostname, socket

serSocket = socket()
server = gethostname()
port = 12345
serSocket.connect((server, port))

data = serSocket.recv(1024)
msg = data.decode('utf-8')
print("Returned Msg from server:  <{}>".format(msg))

serSocket.close()

when the server tries to send the following exception occurred

Traceback (most recent call last):
Got connection from ('192.168.177.1', 49755)
  File "C:/Users/Oren/PycharmProjects/CientServer/ServerSide/Server2.py", line 16, in <module>
    ret_val = s.send("Thank you".encode('utf-8'))
OSError: [WinError 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

Process finished with exit code 1

As can be seen the client connects the server successfully. But send fails.

What is the problem?

The problem is that you are sending on the listening socket, not on the connected socket. connect returns a new socket which is the one you must use for data transfer. The listening socket can never be used for sending or receiving data.

Change the send to this and your program will work fine:

ret_val = c.send("Thank you".encode('utf-8'))

(Note c.send , not s.send )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM