用Python编写程序,实现两个人的聊天,可以是UDP双人聊天,也可以是TCP服务器客户端聊天,要求: (1) 带输入框,能够发送输入的内容 (2) 带显示框,能显示自己发送的内容也能能够接受并显示对方的消息
时间: 2024-02-20 15:02:32 浏览: 57
UDP和TCP实现的聊天程序
好的,我可以为您提供一些思路和代码示例。
首先,您可以选择使用TCP或UDP协议进行双人聊天,这里以TCP为例。
客户端代码示例:
```python
import socket
import threading
def receive_msg(client_socket):
while True:
try:
msg = client_socket.recv(1024).decode('utf-8')
print(msg)
except:
print("Error")
client_socket.close()
break
def send_msg(client_socket):
while True:
try:
msg = input()
client_socket.send(msg.encode('utf-8'))
except:
print("Error")
client_socket.close()
break
if __name__ == '__main__':
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1' # 服务器IP地址
port = 8888 # 服务器端口号
client_socket.connect((host, port))
print("Connected to server")
t1 = threading.Thread(target=receive_msg, args=(client_socket,))
t2 = threading.Thread(target=send_msg, args=(client_socket,))
t1.start()
t2.start()
```
服务器端代码示例:
```python
import socket
import threading
def handle_client(client_socket, client_address):
while True:
try:
msg = client_socket.recv(1024).decode('utf-8')
print(client_address, msg)
for c in clients:
if c != client_socket:
c.send(msg.encode('utf-8'))
except:
print("Error")
client_socket.close()
clients.remove(client_socket)
break
if __name__ == '__main__':
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1' # 服务器IP地址
port = 8888 # 服务器端口号
server_socket.bind((host, port))
server_socket.listen(5)
print("Server started")
clients = []
while True:
client_socket, client_address = server_socket.accept()
clients.append(client_socket)
print("Connected:", client_address)
t = threading.Thread(target=handle_client, args=(client_socket, client_address))
t.start()
```
以上代码仅供参考,您可以根据自己的需要进行修改和完善。
阅读全文