Windows Socket API 实现一个以下功能:客户端实现连接服务端,发送一串字符串后服务端会回一个字符串客户端再进行接收。
时间: 2024-10-27 07:04:12 浏览: 14
要使用Windows Socket API(Winsock)实现客户端和服务端之间的通信,你可以按照以下步骤操作:
**服务端(Server.py)**:
```python
import socket
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置服务器地址和端口
host = "localhost"
port = 12345
# 绑定地址并监听
server_socket.bind((host, port))
server_socket.listen(1)
while True:
# 接受客户端连接
client_socket, addr = server_socket.accept()
try:
# 接收客户端消息
received_data = client_socket.recv(1024)
# 回复消息
response = "Received: " + received_data.decode()
client_socket.sendall(response.encode())
# 关闭客户端连接
client_socket.close()
except Exception as e:
print(f"Error: {e}")
```
**客户端(Client.py)**:
```python
import socket
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置服务器地址和端口
host = "localhost"
port = 12345
try:
# 连接到服务器
client_socket.connect((host, port))
# 发送字符串
message = "Hello from Client!"
client_socket.sendall(message.encode())
# 接收服务端响应
received_data = client_socket.recv(1024).decode()
print(f"Received from Server: {received_data}")
finally:
# 关闭连接
client_socket.close()
```
要在命令行运行这两个程序,首先启动服务端`Server.py`,然后启动客户端`Client.py`。客户端会向服务端发送字符串,服务端接收到后返回一个包含接收到的消息的回复。
阅读全文