基于TCP的程序设计和基于UDP的程序设计及其过程代码
时间: 2024-03-18 22:38:31 浏览: 96
基于TCP的程序设计过程代码:
客户端:
```python
import socket
# 创建TCP连接
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 8000)
client_socket.connect(server_address)
# 发送数据
message = 'Hello, server!'
client_socket.sendall(message.encode())
# 接收数据
data = client_socket.recv(1024)
print('Received:', data.decode())
# 关闭连接
client_socket.close()
```
服务器端:
```python
import socket
# 创建TCP连接
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 8000)
server_socket.bind(server_address)
server_socket.listen(1)
while True:
# 等待客户端连接
print('Waiting for connection...')
client_socket, client_address = server_socket.accept()
# 接收数据
data = client_socket.recv(1024)
print('Received:', data.decode())
# 发送数据
message = 'Hello, client!'
client_socket.sendall(message.encode())
# 关闭连接
client_socket.close()
```
基于UDP的程序设计过程代码:
客户端:
```python
import socket
# 创建UDP连接
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 8000)
# 发送数据
message = 'Hello, server!'
client_socket.sendto(message.encode(), server_address)
# 接收数据
data, server = client_socket.recvfrom(1024)
print('Received:', data.decode())
# 关闭连接
client_socket.close()
```
服务器端:
```python
import socket
# 创建UDP连接
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 8000)
server_socket.bind(server_address)
while True:
# 接收数据
data, client = server_socket.recvfrom(1024)
print('Received:', data.decode())
# 发送数据
message = 'Hello, client!'
server_socket.sendto(message.encode(), client)
```
以上代码仅为示例,实际应用程序中需要根据具体需求进行修改。
阅读全文