0

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?

6
  • Firewall settings? Commented May 7, 2018 at 9:23
  • .encode('utf-8')) why you add that ? you should simply write s.send("Thnaks you") and check your Proxy or Firewall If They Dont Accept the COnnection Commented May 7, 2018 at 9:24
  • @SkillerDz. I encode because a TypeError exception is raised. TypeError: a bytes-like object is required, not 'str' , which I also found in many posts. does this work for u without encoding? Regarding the firewall, I have win 10 and use windows defender firewall. What exactly should i check? I also do not understand, once the connection is established, as in this case, isn't fair to say the firewall is not a problem? Commented May 7, 2018 at 11:28
  • @Mika72 Please see my question above regarding the firewall. Commented May 7, 2018 at 11:35
  • @OJNSim and that is a probleme : serSocket = socket() , use serSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) for a better connection try it for see Commented May 7, 2018 at 11:36

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.