tcpip

admin 550 0

下面是一个简单的使用TCP/IP协议进行通信的Python编程案例:

```python

import socket

# 创建一个TCP/IP套接字

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定套接字到指定的IP地址和端口号

server_address = ('localhost', 8888)

print('启动服务器在 %s 端口 %s 地址上' % server_address)

sock.bind(server_address)

# 监听传入的连接

sock.listen(1)

while True:

print('等待连接...')

connection, client_address = sock.accept()

try:

print('连接来自:', client_address)

# 接收数据

data = connection.recv(1024)

print('接收到的数据:', data.decode())

# 发送响应

response = 'Hello, client!'

connection.sendall(response.encode())

finally:

# 关闭连接

connection.close()

```