当前位置:   article > 正文

Python启动TCP服务并监听连接,从客户端发送消息_python exe 服务监听

python exe 服务监听

下面是一个简单的例子,演示如何在Python中启动TCP服务并监听连接,以及如何从客户端发送消息:

TCP服务端代码:

  1. import socket
  2. HOST = '192.168.6.211'
  3. PORT = 8888
  4. server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  5. server_socket.bind((HOST, PORT))
  6. server_socket.listen()
  7. print(f'Server is listening at {HOST}:{PORT}')
  8. while True:
  9. client_socket, client_address = server_socket.accept()
  10. print(f'Client connected from {client_address}')
  11. message = client_socket.recv(1024).decode('utf-8')
  12. print(f'Received message from client: {message}')
  13. response = 'Hello from server!'
  14. client_socket.send(response.encode('utf-8'))
  15. client_socket.close()

TCP客户端代码:

  1. import socket
  2. HOST = '192.168.6.211'
  3. PORT = 8888
  4. client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  5. client_socket.connect((HOST, PORT))
  6. message = 'Hello from client!'
  7. client_socket.send(message.encode('utf-8'))
  8. response = client_socket.recv(1024).decode('utf-8')
  9. print(f'Received response from server: {response}')
  10. client_socket.close()

这个例子中,服务端首先创建一个socket对象并绑定地址和端口,然后开始监听连接。当客户端连接到服务器时,服务端接受客户端的连接请求并打印客户端地址,然后接收从客户端发送过来的消息,并回复一条消息。客户端首先创建一个socket对象并连接到服务器,然后发送一条消息,并等待接收回复消息。

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/73233
推荐阅读
相关标签
  

闽ICP备14008679号