用python写一个简单的网络编程代码
时间: 2023-08-04 17:38:24 浏览: 51
以下是一个简单的Python网络编程代码,它实现了一个简单的TCP服务器和客户端之间的通信:
服务器端代码:
```python
import socket
# 创建TCP/IP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定服务器地址和端口
server_address = ('localhost', 10000)
print('starting up on %s port %s' % server_address)
sock.bind(server_address)
# 开始监听客户端连接请求
sock.listen(1)
while True:
# 等待客户端连接
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
# 接收客户端数据
while True:
data = connection.recv(1024)
print('received "%s"' % data)
if data:
connection.sendall(data)
else:
break
finally:
# 关闭连接
connection.close()
```
客户端代码:
```python
import socket
# 创建TCP/IP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
server_address = ('localhost', 10000)
print('connecting to %s port %s' % server_address)
sock.connect(server_address)
try:
# 发送数据到服务器
message = 'Hello, world!'
print('sending "%s"' % message)
sock.sendall(message.encode())
# 接收服务器响应
data = sock.recv(1024)
print('received "%s"' % data.decode())
finally:
# 关闭连接
sock.close()
```
以上代码实现了一个简单的TCP服务器和客户端之间的通信,客户端向服务器发送一个消息,服务器返回相同的消息。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)