0

I'm trying to write a program that gets IP adress as an input inside a while loop and makes a TCP connection with it. Here is an example:

import socket
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
 adress=input('Enter the IP:')
 s1.connect((adress, 8000))
 message=input('Enter the message:')
 s1.send(message.encode())
 s1.close()

Server:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind(('', 8000))
s.listen(5)
print('ready')
while True:
 c, addr = s.accept()
 recieved_message= c.recv(1024)
 print(recieved_message.decode())
 c.close()

It successfully makes the first connection and server recieves the first message but when I try to connect it again by inputting the same IP adress I get this error:

[WinError 10038] an operation was attempted on something that is not a socket

I removed s1.close() to outside of the while loop to fix thix but this time I got this error:

[WinError 10056] A connection attempt targeted an already connected socket

I can't find way to solve this. How can I fix this problem?

asked May 18, 2021 at 11:44
0

1 Answer 1

1

The first error is from reusing a closed socket, and the second error is from reconnecting to an already connected socket.

Put the s1 = line inside the while loop in the client to create a new socket for each connection.

import socket
while True:
 s1 = socket.socket()
 address = input('Enter the IP:')
 s1.connect((address, 8000))
 message = input('Enter the message:')
 s1.send(message.encode())
 s1.close()
answered May 18, 2021 at 11:55
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.