基于tcp的通讯录代码
时间: 2024-03-16 16:46:02 浏览: 18
好的,这里是一个简单的基于TCP协议的通讯录代码示例,其中使用Python的socket模块实现了一个简单的客户端-服务器模型。
服务器端代码:
```python
import socket
# 创建TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_socket.bind(('127.0.0.1', 8888))
# 开始监听
server_socket.listen(5)
print('服务器已启动,等待客户端连接...')
while True:
# 等待客户端连接
client_socket, client_address = server_socket.accept()
print('客户端已连接:', client_address)
# 处理客户端请求
while True:
# 接收客户端请求
request = client_socket.recv(1024).decode()
if not request:
break
# 处理请求
if request == 'add':
# 添加联系人
name = client_socket.recv(1024).decode()
phone = client_socket.recv(1024).decode()
# 将联系人信息存储到数据库或文件中
# ...
# 返回添加成功的响应
response = 'Contact added successfully!'
client_socket.send(response.encode())
elif request == 'delete':
# 删除联系人
name = client_socket.recv(1024).decode()
# 从数据库或文件中删除联系人信息
# ...
# 返回删除成功的响应
response = 'Contact deleted successfully!'
client_socket.send(response.encode())
elif request == 'modify':
# 修改联系人
name = client_socket.recv(1024).decode()
phone = client_socket.recv(1024).decode()
# 更新数据库或文件中的联系人信息
# ...
# 返回修改成功的响应
response = 'Contact modified successfully!'
client_socket.send(response.encode())
elif request == 'query':
# 查询联系人
name = client_socket.recv(1024).decode()
# 从数据库或文件中查询联系人信息
# ...
# 返回查询结果
response = 'Name: {}, Phone: {}'.format(name, phone)
client_socket.send(response.encode())
# 关闭客户端连接
client_socket.close()
# 关闭服务器套接字
server_socket.close()
```
客户端代码:
```python
import socket
# 创建TCP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
server_address = ('127.0.0.1', 8888)
client_socket.connect(server_address)
while True:
# 发送请求
request = input('请输入请求(add/delete/modify/query): ')
client_socket.send(request.encode())
if request == 'add':
# 添加联系人
name = input('请输入姓名: ')
phone = input('请输入电话号码: ')
client_socket.send(name.encode())
client_socket.send(phone.encode())
# 接收响应
response = client_socket.recv(1024).decode()
print(response)
elif request == 'delete':
# 删除联系人
name = input('请输入姓名: ')
client_socket.send(name.encode())
# 接收响应
response = client_socket.recv(1024).decode()
print(response)
elif request == 'modify':
# 修改联系人
name = input('请输入姓名: ')
phone = input('请输入电话号码: ')
client_socket.send(name.encode())
client_socket.send(phone.encode())
# 接收响应
response = client_socket.recv(1024).decode()
print(response)
elif request == 'query':
# 查询联系人
name = input('请输入姓名: ')
client_socket.send(name.encode())
# 接收响应
response = client_socket.recv(1024).decode()
print(response)
# 关闭客户端套接字
client_socket.close()
```
这只是一个简单的示例,实际应用中还需要考虑很多细节和异常情况的处理。