python tcp server demo
时间: 2024-01-13 18:52:47 浏览: 28
Sure, I can help you with that. Here's a simple Python TCP server demo:
```
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to a specific address and port
s.bind((HOST, PORT))
# Listen for incoming connections (max queue size = 1)
s.listen(1)
# Wait for a client connection
print('Waiting for a client connection...')
conn, addr = s.accept()
print('Connected by', addr)
# Receive and print data from the client
while True:
data = conn.recv(1024)
if not data: break
print('Received data:', data.decode())
# Close the connection
conn.close()
```
This server listens on port 8888 and waits for incoming client connections. Once a client connects, it receives data from the client and prints it to the console.