写一对TCP套接字编程的python程序,要求实现客户端发送一行字符串数据给服务器端,服务器返回大写字符串。要求服务器端打印客户端发送的数据,打印客户端发起TCP连接的IP地址和端口号;客户端打印建立连接的服务器端的IP地址和端口号,打印服务器返回的大写字符串;
时间: 2024-05-05 13:20:23 浏览: 11
好的,我理解了您的要求。以下是您需要的Python程序示例:
服务器端代码:
```python
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8080))
server_socket.listen(1)
print("Waiting for client connection...")
while True:
connection, address = server_socket.accept()
print(f"Connected to {address[0]}:{address[1]}")
data = connection.recv(1024)
if data:
print(f"Received from client: {data.decode()}")
connection.send(data.upper())
connection.close()
```
客户端代码:
```python
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8080))
print(f"Connected to server at {client_socket.getpeername()[0]}:{client_socket.getpeername()[1]}")
client_socket.sendall(b"hello server")
data = client_socket.recv(1024)
print(f"Received from server: {data.decode()}")
client_socket.close()
```
请注意,这个程序仅仅是一个示例。在实际的生产环境中,还需要加入更多的错误处理、异常处理、日志记录等功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)