写服务端和客户端,使双方可以互发一条信息,显示收到信息后退出
时间: 2024-10-13 13:08:45 浏览: 12
简单的java socket客户端和服务端示例
创建一个简单的服务器和客户端程序,以便在两方之间发送消息并在接收到消息后退出,通常涉及网络编程。这里我们将以Python的socket库为例来说明:
### 服务器端(server.py)
```python
import socket
# 创建套接字并指定地址和端口
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 12345)
backlog = 5 # 队列最大长度
# 绑定并监听连接
server_socket.bind(server_address)
server_socket.listen(backlog)
print(f"Server started on {server_address}.")
while True:
# 接受客户端连接
client_connection, client_address = server_socket.accept()
print(f"Accepted connection from {client_address}.")
try:
# 接收客户端消息,并回显给客户端
message = client_connection.recv(1024).decode('utf-8')
print(f"Received: {message}")
client_connection.sendall(message.encode('utf-8'))
# 客户端收到消息后关闭连接,表示退出
client_connection.close()
print("Client disconnected.")
except Exception as e:
print(f"Error: {e}")
```
### 客户端(client.py)
```python
import socket
def send_message():
host = 'localhost'
port = 12345
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((host, port))
try:
# 输入要发送的消息
message = input("Enter a message to send: ")
sock.sendall(message.encode('utf-8'))
# 接收服务器响应
response = sock.recv(1024).decode('utf-8')
print(f"Response received: {response}")
finally:
sock.close()
if __name__ == "__main__":
send_message()
print("Client disconnected after receiving message.")
```
**运行流程:**
1. 启动服务器(`server.py`),等待客户端连接。
2. 客户端连接到服务器,输入消息并发送。
3. 服务器接收并回显消息给客户端。
4. 客户端读取服务器响应后,关闭连接。
**相关问题:**
1. 这种交互适用于哪种场景?
2. 如果需要增加多个客户端连接,应该怎么做?
3. 如何在服务器端处理并发连接?
阅读全文