Python - Simple TCP Server and Client
# Server Code
import socket, sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 10000
sock.bind(("127.0.0.1", port))
sock.listen(1)
print("Starting Server...")
while True:
conn, (addr, port) = sock.accept()
data = conn.recv(port)
data = ("Server received your message: " + data.decode()).encode()
conn.sendall(data)
conn.close()
# Client Code
import socket
message = "Hi. How are you?"
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 10000))
client.send(message.encode())
messageFromServer = client.recv(1024)
client.close()
print (messageFromServer)
Comments
Post a Comment