Python으로 구현된 WebSocket 서버측

5024 단어 WebSocket
문서 목록
  • 1. 누르기
  • 2. 라이브러리 설치
  • 3. 코드
  • 1. 누르다
    하나의 프로젝트가 여러 언어로 개발되어야 한다면 참고하십시오:WebSocket 기반의 분포식 마이크로코어 프로젝트
    2. 라이브러리 설치
    You can use the project in three ways:
  • Copy/paste the websocket_server.py file in your project and use it directly
  • pip install git+https://github.com/Pithikos/python-websocket-server
    
    (latest code)
  • pip install websocket-server
    
    (might not be up-to-date)

  • GitHub:https://github.com/Pithikos/python-websocket-server
    3. 코드
    from websocket_server import WebsocketServer
    
    # Called for every client connecting (after handshake)
    def new_client(client, server):
    	print("New client connected and was given id %d" % client['id'])
    	server.send_message_to_all("Hey all, a new client has joined us")
    
    
    # Called for every client disconnecting
    def client_left(client, server):
    	print("Client(%d) disconnected" % client['id'])
    
    
    # Called when a client sends a message
    def message_received(client, server, message):
    	if len(message) > 200:
    		message = message[:200]+'..'
    	print("Client(%d) said: %s" % (client['id'], message))
    
    
    PORT=56
    server = WebsocketServer(PORT,host='0.0.0.0')
    server.set_fn_new_client(new_client)
    server.set_fn_client_left(client_left)
    server.set_fn_message_received(message_received)
    print("    ")
    server.run_forever()
    

    좋은 웹페이지 즐겨찾기