用python编写客户端和服务端代码,写一个简单的chat程序 要求:1、传输服务能自由选择TCP或STP,在启动的时候配置,交互双方须统一; 2、能互发消息,互传文件; 3、简单测试一下分别采用TCP和STP时,程序的运行表现。 4、编程语言为python。
时间: 2024-10-28 18:11:56 浏览: 40
在Python中,我们可以使用socket库来编写简单的客户端和服务器端的聊天程序,支持TCP和UDP(User Datagram Protocol,用户数据报协议)。这里是一个简化的示例,展示如何创建一个基本的聊天系统:
**服务器端(server.py):**
```python
import socket
from threading import Thread
# 配置服务器地址和端口
if input("请选择通信协议(TCP/UDP): ").lower() == 'tcp':
family = socket.AF_INET
proto = socket.SOCK_STREAM
else:
family = socket.AF_INET
proto = socket.SOCK_DGRAM
server_address = ('localhost', 9999)
if __name__ == "__main__":
server = socket.socket(family, proto)
if proto == socket.SOCK_STREAM:
server.bind(server_address)
print(f"Server started on {server_address} (TCP)")
else:
server.bind(("", 0)) # UDP server listens on any available port
print(f"Server started on {server_address} (UDP)")
if proto == socket.SOCK_STREAM:
while True:
client, addr = server.accept()
print(f"Accepted connection from {addr}")
client_handler = Thread(target=handle_client, args=(client,))
client_handler.start()
else:
while True:
data, addr = server.recvfrom(1024)
print(f"Received message from {addr}: {data.decode('utf-8')}")
server.sendto(data, addr) # Echo back the message to sender
def handle_client(client):
try:
while True:
msg = client.recv(1024)
if not msg: break
server.sendall(msg) # Forward the message to all connected clients in UDP mode
finally:
client.close()
```
**客户端(client.py):**
```python
import socket
import os
if input("请选择通信协议(TCP/UDP): ").lower() == 'tcp':
family = socket.AF_INET
proto = socket.SOCK_STREAM
else:
family = socket.AF_INET
proto = socket.SOCK_DGRAM
client_address = ('localhost', 9999)
if __name__ == "__main__":
with socket.socket(family, proto) as sock:
if proto == socket.SOCK_STREAM:
sock.connect(server_address)
print(f"Connected to {server_address} (TCP)")
else:
sock.sendto(b"Hello, Server!", server_address)
print(f"Sent message to {server_address} (UDP)")
while True:
msg = input("Enter your message: ")
if msg.lower() == "exit":
break
sock.send(msg.encode('utf-8'))
if proto == socket.SOCK_STREAM:
response = sock.recv(1024).decode('utf-8')
else:
response = None # UDP doesn't guarantee message delivery
if response:
print(response)
sock.close()
```
要在不同协议下测试程序,你可以分别运行`server.py`(选择TCP或UDP)和`client.py`(也选择相同的协议),然后开始交流。注意,由于UDP是非连接的,它不保证消息的顺序和可靠性,所以在发送文件时可能会有丢失或乱序。
阅读全文