python websocket server

本文介绍了一个使用 Python 和 Tornado 框架实现的简单 WebSocket 服务器。通过安装 Tornado 并运行提供的 Python 脚本,可以快速搭建起一个 WebSocket 服务器及客户端交互示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Simple WebSocket Server in Python

via: http://www.remwebdevelopment.com/blog/python/simple-websocket-server-in-python-144.html

This sample uses Tornado, which is a socket server module for Python. I found this sample code here. I modified the python script very slightly, and pretty much completely overhauled the html page.

 

To install Tornado, it's easiest to do it via the python package manager (pip). So here is how I installed both pip and tornado from the command line:

sudo apt-get install python-pip

pip install tornado

 

 

Once you've done that you can download and unzip the files:

 python-socket-server-and-client.zip 

Or, if you'd like to review the code before downloading, look down the page. It's only two files and they are both pretty simple.

 

To try it out just unzip the files in a directory, then cd to that directory and enter:

python websocket-server.py

 

This will start the web socket server. Now open up your browser and enter this in the url bar: localhost:9090

 

If you want to run the client from a different machine (not the one that is running the websocket server), you'll have to adjust the 'host' variable in index.html

 

Here is the code for the server (websocket-server.py) :

import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.template

class MainHandler(tornado.web.RequestHandler):
  def get(self):
    loader = tornado.template.Loader(".")
    self.write(loader.load("index.html").generate())

class WSHandler(tornado.websocket.WebSocketHandler):
  def open(self):
    print 'connection opened...'
    self.write_message("The server says: 'Hello'. Connection was accepted.")

  def on_message(self, message):
    self.write_message("The server says: " + message + " back at you")
    print 'received:', message

  def on_close(self):
    print 'connection closed...'

application = tornado.web.Application([
  (r'/ws', WSHandler),
  (r'/', MainHandler),
  (r"/(.*)", tornado.web.StaticFileHandler, {"path": "./resources"}),
])

if __name__ == "__main__":
  application.listen(9090)
  tornado.ioloop.IOLoop.instance().start()

 

 

And here is index.html

<!DOCTYPE html>
<html>
<head>
  <title>WebSockets Client</title>  
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
Enter text to send to the websocket server:
<div id="send">
    <input type="text" id="data" size="100"/><br>
    <input type="button" id="sendtext" value="send text"/>
</div>
<div id="output"></div>
</body>
</html>
<script>

jQuery(function($){

  if (!("WebSocket" in window)) {
    alert("Your browser does not support web sockets");
  }else{
    setup();
  }


  function setup(){
   
    // Note: You have to change the host var 
    // if your client runs on a different machine than the websocket server
    
    var host = "ws://localhost:9090/ws";
    var socket = new WebSocket(host);
    //console.log("socket status: " + socket.readyState);   
    
    var $txt = $("#data");
    var $btnSend = $("#sendtext");

    $txt.focus();

    // event handlers for UI
    $btnSend.on('click',function(){
      var text = $txt.val();
      if(text == ""){
        return;
      }
      socket.send(text);
      $txt.val("");    
    });

    $txt.keypress(function(evt){
      if(evt.which == 13){
        $btnSend.click();
      }
    });

    // event handlers for websocket
    if(socket){

      socket.onopen = function(){
        //alert("connection opened....");
      }

      socket.onmessage = function(msg){
        showServerResponse(msg.data);
      }

      socket.onclose = function(){
        //alert("connection closed....");
        showServerResponse("The connection has been closed.");
      }

    }else{
      console.log("invalid socket");
    }

    function showServerResponse(txt){
      var p = document.createElement('p');
      p.innerHTML = txt;
      document.getElementById('output').appendChild(p); 
    }	


  }

});

</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值