python tcp 服务端
时间: 2023-11-13 09:54:48 浏览: 97
好的,以下是 Python TCP 服务端的代码示例:
```python
import socket
HOST = '127.0.0.1' # 监听的IP地址
PORT = 8888 # 监听的端口号
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_socket.bind((HOST, PORT))
# 开始监听
server_socket.listen(1)
print('等待客户端连接...')
# 等待客户端连接
client_socket, client_address = server_socket.accept()
print('客户端已连接:', client_address)
while True:
# 接收客户端发送的数据
data = client_socket.recv(1024)
if not data:
break
print('收到客户端消息:', data.decode())
# 发送响应数据给客户端
response = 'Hello, client!'
client_socket.sendall(response.encode())
# 关闭连接
client_socket.close()
server_socket.close()
```
相关问题
python TCP服务端
Python 中创建一个简单的 TCP 服务端可以使用内置的 socket 模块。以下是一个基本的服务器示例,它监听在一个特定的端口上,等待客户端连接,并接收来自客户端的消息:
```python
import socket
# 创建套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置服务器地址和端口
host = 'localhost'
port = 12345
# 绑定端口
server_socket.bind((host, port))
# 开始监听连接
server_socket.listen(1) # 最大排队连接数为1
print(f"Server is running on {host}:{port}")
while True:
# 接受客户端连接
client_socket, address = server_socket.accept()
print(f"Accepted connection from {address}:{address[1]}")
# 收取客户端数据
request_data = client_socket.recv(1024)
print(f"Received data: {request_data.decode()}")
# 发送响应(这里只发送一个固定的回复)
response = "Hello from the server!"
client_socket.sendall(response.encode())
# 关闭客户端连接
client_socket.close()
```
这个例子中,服务器会持续运行,直到手动停止。每次有新的客户端连接,服务器都会接受请求并发送一个固定的响应。
python TCP服务端接收多个客户端数据的程序
可以通过多线程或者异步IO实现TCP服务端接收多个客户端数据,以下是一个基于多线程的示例程序:
```python
import socket
import threading
def handle_client(client_socket):
while True:
data = client_socket.recv(1024)
if not data:
break
# 处理客户端数据
response = b"Hello, client!"
client_socket.send(response)
client_socket.close()
def run_server():
host = "127.0.0.1"
port = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
print(f"Listening on {host}:{port}...")
while True:
client_socket, client_address = server_socket.accept()
print(f"Accepted connection from {client_address[0]}:{client_address[1]}")
client_handler = threading.Thread(target=handle_client, args=(client_socket,))
client_handler.start()
if __name__ == "__main__":
run_server()
```
此程序会监听本地8888端口,处每个客户端连接会启动一个新的线程来处理客户端数据。
阅读全文