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?
1 Answer 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()