TCP套接字编程代码
时间: 2024-11-06 13:09:30 浏览: 14
Python网络编程之TCP套接字简单用法示例
TCP(Transmission Control Protocol)套接字编程通常涉及客户端和服务器两个部分。这里是一个简单的Python例子,展示了一个基本的TCP服务器和客户端程序:
**服务器端代码** (server.py):
```python
import socket
# 创建socket对象
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口
server.bind(('localhost', 12345))
# 开始监听连接
server.listen(1)
print("Server is listening...")
while True:
# 等待客户端连接
client, addr = server.accept()
print(f"Accepted connection from {addr[0]}:{addr[1]}")
# 接收客户端数据并发送回应
data = client.recv(1024)
if not data:
break
print("Received:", data.decode())
client.sendall("Hello, Client!".encode())
# 关闭连接
client.close()
```
**客户端代码** (client.py):
```python
import socket
# 创建socket对象
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务器
client.connect(('localhost', 12345))
# 发送数据到服务器
message = "Hello, Server!"
client.sendall(message.encode())
# 接收服务器响应
response = client.recv(1024)
print("Received:", response.decode())
# 关闭连接
client.close()
```
阅读全文