python实现匿名聊天、匿名名字定制的思路
时间: 2023-10-10 18:11:01 浏览: 28
Python实现匿名聊天、匿名名字定制的思路和匿名聊天基本一致,只需要在客户端输入用户名时,增加一个判断,如果用户输入了空字符串,则随机生成一个匿名用户名。具体思路如下:
1. 客户端连接服务器后,输入用户名。
2. 判断用户名是否为空字符串,如果是,则生成一个随机的匿名用户名。
3. 发送用户名给服务器,并等待服务器的确认。
4. 客户端输入消息后,将消息和用户名一起发送给服务器。
5. 服务器接收到消息后,将消息和发送者的用户名一起广播给所有客户端。
以下是一个简单的示例代码,实现了匿名聊天和匿名名字定制:
```python
import socket
import threading
import random
def send_message():
while True:
message = input()
if not message:
continue
if username is None:
username = 'Anonymous{}'.format(random.randint(1000, 9999))
client_socket.send(username.encode())
response = client_socket.recv(1024).decode()
print(response)
client_socket.send('{}: {}'.format(username, message).encode())
def receive_message():
while True:
message = client_socket.recv(1024).decode()
print(message)
# 创建socket对象
client_socket = socket.socket()
# 获取服务器IP地址和端口号
server_ip = input("请输入服务器IP地址:")
server_port = int(input("请输入服务器端口号:"))
# 连接服务器
client_socket.connect((server_ip, server_port))
# 输入用户名
username = input("请输入用户名(按回车键使用匿名用户):")
# 创建发送消息线程和接收消息线程
send_thread = threading.Thread(target=send_message)
receive_thread = threading.Thread(target=receive_message)
# 启动线程
send_thread.start()
receive_thread.start()
```
这段代码中,如果用户输入了空字符串,则生成一个随机的匿名用户名,格式为"Anonymous"加上4位随机数字。客户端发送用户名给服务器后,等待服务器的确认,并打印出来。客户端发送消息时,将消息和用户名一起发送给服务器。服务器接收到消息后,将消息和发送者的用户名一起广播给所有客户端。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)