18

I am working on this code

from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(2)

while 1:
    print ("waiting on connection")
    clientsock, addr = serversock.accept()
    print ('connected from:', addr)
    while 1:
        data = clientsock.recv(1024).decode()
        if not data: break 
        clientsock.send(data.encode())
        clientsock.close()

serversock.close()

I get this error:

OSError: [WinError 10038] an operation was attempted on something that is not a socket
3
  • Does it tell you what line the error is on? Is there any other info you can post to give an idea what's going on, what you're trying to do, aside from create a network connection? Commented Mar 4, 2013 at 20:31
  • i got this error when running flask from cmd within PyCharm. Switched to Windows CMD Window and the error is gone. Commented May 5, 2020 at 9:48
  • 1
    I got this error when trying to run flask in a separate process. I get this error regardless if I run within PyCharm or from Windows cmd prompt. Running flask as a blocking process in Pycharm works fine for me. Commented Apr 19, 2023 at 14:36

3 Answers 3

28

You are closing the clientsock after reading only part of the data.

clientsock.close()

is at the wrong level of indentation. Move it to the left by one step.

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

2 Comments

i wonder why that line (connection close) is executed while previous line (send data) execution is not completed!
@MohammadGhorbani a bit late, but it's because the clientsock.send() is non-blocking; it doesn't wait for that function to complete before moving on (I think).
3

The problem is with close(). after connection get close you need to initialize the connection again

add this line inside while loop

serversock = socket(AF_INET, SOCK_STREAM)

Comments

-3

Besides the close problem, you need to run:

WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);

before the call to socket

1 Comment

can you explain why? also that looks like the wrong language, the question was about python

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.