tcpclient程序示例
时间: 2024-10-14 19:02:17 浏览: 12
TcpClient通信Demo
TCPClient是一个简单的网络应用程序,用于通过TCP协议连接到远程服务器并发送数据。下面是一个基本的Python TCP客户端示例,它使用socket库:
```python
import socket
def send_message(host, port, message):
# 创建一个TCP/IP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# 连接到指定主机和端口
client_socket.connect((host, port))
# 发送消息
client_socket.sendall(message.encode('utf-8'))
# 接收服务器响应
response = client_socket.recv(1024)
print("Received from server:", response.decode('utf-8'))
except ConnectionRefusedError:
print(f"Connection refused by {host}:{port}.")
finally:
# 关闭连接
client_socket.close()
# 示例:向www.example.com的80端口发送一条消息
send_message("www.example.com", 80, "Hello, Server!")
阅读全文