理解传输层两个通信协议TCP与UDP 掌握简单UDP通信程序的编写 掌握简单TCP通信程序的编写 掌握简单多线程通信程序的编写 实验要求 理解TCP与UDP协议的基本概念 使用python实现UDP和TCP的简单通信过程python代码
时间: 2024-03-19 15:43:19 浏览: 70
网络安全技术- TCPIP-02 传输层的两个协议TCP和UDP.mp3
以下是Python实现UDP和TCP的简单通信过程的示例代码:
UDP服务器端代码:
```python
import socket
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定IP地址和端口号
server_address = ('127.0.0.1', 8888)
server_socket.bind(server_address)
# 接收数据
data, client_address = server_socket.recvfrom(1024)
# 打印接收到的数据
print('Received:', data.decode())
# 发送数据
message = 'Hello, client!'
server_socket.sendto(message.encode(), client_address)
# 关闭socket连接
server_socket.close()
```
UDP客户端代码:
```python
import socket
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据
message = 'Hello, server!'
client_address = ('127.0.0.1', 8888)
client_socket.sendto(message.encode(), client_address)
# 接收数据
data, server_address = client_socket.recvfrom(1024)
# 打印接收到的数据
print('Received:', data.decode())
# 关闭socket连接
client_socket.close()
```
TCP服务器端代码:
```python
import socket
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_address = ('127.0.0.1', 8888)
server_socket.bind(server_address)
# 监听客户端连接
server_socket.listen(1)
# 等待客户端连接
print('Waiting for client connection...')
client_socket, client_address = server_socket.accept()
print('Client connected:', client_address)
# 接收数据
data = client_socket.recv(1024)
# 打印接收到的数据
print('Received:', data.decode())
# 发送数据
message = 'Hello, client!'
client_socket.sendall(message.encode())
# 关闭socket连接
client_socket.close()
server_socket.close()
```
TCP客户端代码:
```python
import socket
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
server_address = ('127.0.0.1', 8888)
client_socket.connect(server_address)
# 发送数据
message = 'Hello, server!'
client_socket.sendall(message.encode())
# 接收数据
data = client_socket.recv(1024)
# 打印接收到的数据
print('Received:', data.decode())
# 关闭socket连接
client_socket.close()
```
以上代码仅供参考,实际使用中还需要根据具体需求进行修改和完善。
阅读全文