Série: sockets
python
53 linhas
· Atualizado 2026-02-03
02-basic-tcp-client.py
sockets/examples/python/02-basic-tcp-client.py
#!/usr/bin/env python3
"""
Basic TCP Client
A simple TCP client that connects to a server and sends a message.
"""
import socket
import sys
# Configuration
HOST = 'localhost'
PORT = 8080
def main():
# Create TCP socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server
print(f"Connecting to {HOST}:{PORT}...")
client.connect((HOST, PORT))
print("Connected!")
# Send message
message = "Hello, Server!"
print(f"Sending: {message}")
client.sendall(message.encode('utf-8'))
# Receive response
response = client.recv(1024)
if response:
print(f"Received: {response.decode('utf-8')}")
else:
print("Server closed connection")
except ConnectionRefusedError:
print(f"Error: Connection refused.")
print("Make sure the server is running on {}:{}".format(HOST, PORT))
sys.exit(1)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
finally:
# Close connection
client.close()
print("Connection closed")
if __name__ == '__main__':
main()
Artigos relacionados
sockets
c
Atualizado 2026-02-05
01-basic-tcp-server.c
01-basic-tcp-server.c — c source code from the sockets learning materials (sockets/examples/c/01-basic-tcp-server.c).
Ler artigo →
sockets
c
Atualizado 2026-02-05
02-basic-tcp-client.c
02-basic-tcp-client.c — c source code from the sockets learning materials (sockets/examples/c/02-basic-tcp-client.c).
Ler artigo →
sockets
c
Atualizado 2026-02-05
03-basic-udp-server.c
03-basic-udp-server.c — c source code from the sockets learning materials (sockets/examples/c/03-basic-udp-server.c).
Ler artigo →
sockets
c
Atualizado 2026-02-05
04-basic-udp-client.c
04-basic-udp-client.c — c source code from the sockets learning materials (sockets/examples/c/04-basic-udp-client.c).
Ler artigo →
sockets
c
Atualizado 2026-02-05
05-https-client.c
05-https-client.c — c source code from the sockets learning materials (sockets/examples/c/05-https-client.c).
Ler artigo →
sockets
c
Atualizado 2026-02-05
06-domain-to-ip.c
06-domain-to-ip.c — c source code from the sockets learning materials (sockets/examples/c/06-domain-to-ip.c).
Ler artigo →