能分为客户端和服务器来实现吗
时间: 2024-01-31 12:03:49 浏览: 24
当然可以,以下是一个使用 Python socket 实现的简单在线聊天机器人的客户端和服务器端的代码实现。
服务器端:
```python
import socket
# 创建套接字
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
host = socket.gethostname()
# 设置端口号
port = 9999
# 绑定端口号
s.bind((host, port))
# 设置最大连接数,超过后排队
s.listen(5)
print('聊天机器人已启动...')
while True:
# 建立客户端连接
clientsocket, addr = s.accept()
print("连接地址:%s" % str(addr))
msg = '欢迎访问我的聊天机器人!' + "\r\n"
clientsocket.send(msg.encode('utf-8'))
while True:
data = clientsocket.recv(1024).decode('utf-8')
print("客户端消息:%s" % str(data))
# 判断客户端消息是否为空
if not data:
break
# 回复消息
reply = '你说了:%s' % data + "\r\n"
clientsocket.send(reply.encode('utf-8'))
clientsocket.close()
```
客户端:
```python
import socket
# 创建套接字
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
host = socket.gethostname()
# 设置端口号
port = 9999
# 连接服务器
s.connect((host, port))
while True:
# 发送消息
message = input("请输入要发送的消息:")
s.send(message.encode('utf-8'))
# 接收消息
data = s.recv(1024).decode('utf-8')
print("服务器回复:%s" % str(data))
s.close()
```
在客户端代码中,我们使用 `connect()` 函数连接到服务器。然后,我们使用 `while` 循环等待用户输入消息并将其发送到服务器。一旦接收到服务器的回复,我们将其打印到控制台中。
请注意,该程序仍然只提供了基本的功能,您可以根据需要进行修改和扩展。例如,您可以在客户端代码中实现更高级的用户界面和输入验证。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)