The simplest Python socket client-server example
suggest changeServer side:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.bind(("localhost", 8089))
server_socket.listen()
connection, address = server_socket.accept()
with connection:
message = connection.recv(64)
print(message.decode("utf-8"))
Client Side:
import socket
with socket.create_connection(("localhost", 8089)) as client_socket:
client_socket.sendall("hello".encode("utf-8"))
Run the server first, then run the client. Python 3 sockets exchange bytes, so the client encodes text before sending it and the server decodes received bytes.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents