编写一个tcp服务端程序server和客户端程序client。并利用poll()函数实现客户端和服务端同时监听标准输入和套接字。
时间: 2024-12-24 15:35:17 浏览: 4
在编写TCP服务器和客户端程序时,我们可以使用Python的socket库来创建网络连接。以下是简单的例子:
**Server端(server.py)**
```python
import socket
import select
def server():
host = 'localhost'
port = 9000
backlog = 5
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(backlog)
sockets_to_poll = [server_socket]
while True:
readable, writable, exceptional = select.select(sockets_to_poll, [], sockets_to_poll)
for sock in readable:
if sock == server_socket:
client, addr = server_socket.accept()
print(f"Accepted connection from {addr}")
sockets_to_poll.append(client)
else:
data = sock.recv(1024)
if not data:
print("Client disconnected")
sockets_to_poll.remove(sock)
else:
print(f"Received message: {data.decode('utf-8')}")
sock.sendall(data)
if __name__ == "__main__":
server()
```
**客户端(client.py)**
```python
import socket
import select
def client(host, port):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
sockets_to_poll = [sys.stdin, client_socket]
while True:
readable, writable, exceptional = select.select(sockets_to_poll, [], sockets_to_poll)
for sock in readable:
if sock == sys.stdin:
msg = input("Enter a message: ")
client_socket.sendall(msg.encode('utf-8'))
elif sock == client_socket:
data = sock.recv(1024)
if not data:
break
print(f"Received message: {data.decode('utf-8')}")
if __name__ == "__main__":
host = 'localhost'
port = 9000
client(host, port)
```
在这个例子中,`select.poll()`函数用于监控指定的文件描述符集合,当它们变得可读、可写或出错时,就会触发相应的回调。服务器会同时监听标准输入和新连接的客户端,客户端则在标准输入和服务器之间交互。
阅读全文