Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am writing a simple socket app, and I have met this message and don't know how to fix it.
server_input =s.recv(1024)
ConnectionResetError: [Errno 54] Connection reset by peer
server.py
import socket
def main():
s = socket.socket()
port = 58257
client_address = "localhost"
s.bind((client_address, port))
s.listen(2)
user_input = input("Enter a message: ")
s.send(user_input.encode())
s.close()
if __name__ == '__main__':
main()
client.py
import socket
def main():
s = socket.socket()
#host = socket.gethostname()
port = 58257
client_address = "localhost"
s.connect((client_address, port))
print("connet ")
server_input =s.recv(1024)
server_input.decode()
print("Received message: " + server_input)
s.close()
if __name__ == '__main__':
main()
It is there any problem with my code? Thank you so much!!!
s.send(user_input.encode())
The server needs to call accept
on the server socket to get a socket for the connected client, then call send
on this connected socket, not on the server socket.
Without this the connect
in the client will still succeed, since it is done by the OS kernel on the server side. But since the connected socket is never accept
ed by the server it will be reset, thus resulting in the error you see.
So a more correct code on the server side would be
s.listen(2)
c,_ = s.accept()
user_input = input("Enter a message: ")
c.send(user_input.encode())
c.close()
Note that your client code has also other problems, i.e it should be
print("Received message: " + server_input.decode())
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.