socket发送和接收程序实例
时间: 2023-09-16 08:06:29 浏览: 102
Socket传输实例
以下是一个简单的Socket发送和接收程序实例,使用Python语言实现。
发送端程序:
```python
import socket
# 创建TCP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
server_address = ('localhost', 8888)
client_socket.connect(server_address)
# 发送数据
message = 'Hello, server!'
client_socket.sendall(message.encode())
# 关闭套接字
client_socket.close()
```
接收端程序:
```python
import socket
# 创建TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 监听连接
server_socket.listen(1)
# 等待客户端连接
print('waiting for connection...')
client_socket, client_address = server_socket.accept()
print('connected from', client_address)
# 接收数据
data = client_socket.recv(1024)
print('received:', data.decode())
# 关闭套接字
client_socket.close()
server_socket.close()
```
阅读全文