给出TCP/IP通信中,如何实现一个SEVER和多个clint间通讯的详细代码
时间: 2024-02-23 18:03:33 浏览: 141
以下是一个使用Python的TCP/IP通信的示例代码,其中包括一个服务器和多个客户端的通讯实现:
服务器端代码:
```python
import socket
import threading
SERVER_HOST = '0.0.0.0'
SERVER_PORT = 8000
BUFFER_SIZE = 1024
def handle_client(client_socket, client_address):
print(f'New connection from {client_address}')
while True:
data = client_socket.recv(BUFFER_SIZE)
if not data:
print(f'Connection closed by {client_address}')
break
message = data.decode('utf-8')
print(f'Received message from {client_address}: {message}')
response = f'Received message: {message}'.encode('utf-8')
client_socket.send(response)
client_socket.close()
def run_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.bind((SERVER_HOST, SERVER_PORT))
server_socket.listen(5)
print(f'Server started on {SERVER_HOST}:{SERVER_PORT}')
while True:
client_socket, client_address = server_socket.accept()
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_thread.start()
if __name__ == '__main__':
run_server()
```
客户端代码:
```python
import socket
SERVER_HOST = 'localhost'
SERVER_PORT = 8000
BUFFER_SIZE = 1024
def run_client():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((SERVER_HOST, SERVER_PORT))
print(f'Connected to server {SERVER_HOST}:{SERVER_PORT}')
while True:
message = input('Input message (q to quit): ')
if message == 'q':
break
client_socket.send(message.encode('utf-8'))
response = client_socket.recv(BUFFER_SIZE)
print(f'Received response from server: {response.decode("utf-8")}')
if __name__ == '__main__':
run_client()
```
以上代码实现了一个简单的TCP/IP通信,服务器可以接收多个客户端的连接,并为每个客户端创建一个新的线程进行服务,客户端可以向服务器发送消息并接收服务器的响应。
阅读全文