用tcp实现字符大小写转换
时间: 2024-02-18 19:05:43 浏览: 21
以下是使用TCP实现字符大小写转换的Python代码示例:
服务端代码:
```python
import socket
# 创建TCP Socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_address = ('localhost', 8000)
server_socket.bind(server_address)
# 监听客户端连接请求
server_socket.listen(1)
print('等待客户端连接...')
while True:
# 接收客户端连接请求
client_socket, client_address = server_socket.accept()
print('客户端已连接:{}'.format(client_address))
while True:
# 接收客户端发送的数据
data = client_socket.recv(1024).decode().strip()
if not data:
break
# 将字符转换为大写或小写
if data.isupper():
data = data.lower()
else:
data = data.upper()
# 发送转换后的数据给客户端
client_socket.sendall(data.encode())
# 关闭客户端连接
client_socket.close()
```
客户端代码:
```python
import socket
# 创建TCP Socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务端
server_address = ('localhost', 8000)
client_socket.connect(server_address)
while True:
# 获取用户输入
data = input('请输入字符串(输入q退出):')
if data == 'q':
break
# 发送数据给服务端
client_socket.sendall(data.encode())
# 接收服务端发送的数据
data = client_socket.recv(1024).decode().strip()
print('转换后的字符串:{}'.format(data))
# 关闭连接
client_socket.close()
```
运行服务端代码和客户端代码后,可以输入字符串进行大小写转换,并且服务端会将转换后的字符串发送给客户端。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)