Tips: 本文创建于2016年5月12日,已超过 2 年,内容或图片可能已经失效!

python websocket 聊天实例

后端python

#! /usr/bin/env python  
# -*- coding: utf-8 -*-  
# vim:fenc=utf-8  
#  
# pip install bottle_websocket  
# pip install bottle  
from bottle import get, run, template  
from bottle.ext.websocket import GeventWebSocketServer  
from bottle.ext.websocket import websocket  
import gevent  
users = set()  
@get('/')  
def index():  
    return template('index')  
@get('/websocket', apply=[websocket])  
def chat(ws):  
    users.add(ws)  
    while True:  
        msg = ws.receive()  
        if msg is not None:  
            for u in users:  
                print type(u)  
                u.send(msg)  
                print u,msg  
        else: break  
    users.remove(ws)  
run(host='192.168.36.67', port=10000, server=GeventWebSocketServer) 

前端代码

<html>  
<head>  
<script type="text/javascript" src="http://cdn.staticfile.org/jquery/1.11.0/jquery.min.js"></script>  
<script>  
        $(document).ready(function() {  
            if (!window.WebSocket) {  
                if (window.MozWebSocket) {  
                    windowwindow.WebSocket = window.MozWebSocket;  
                } else {  
                    $('#messages').append("<li>Your browser doesn't support WebSockets.</li>");  
                }  
            }  
            ws = new WebSocket('ws://192.168.36.67:10000/websocket');  
            ws.onopen = function(evt) {  
                $('#messages').append('<li>Connected to chat.</li>');  
            }  
            ws.onmessage = function(evt) {  
                $('#messages').append('<li>' + evt.data + '</li>');  
            }  
            $('#send-message').submit(function() {  
                ws.send($('#name').val() + ": " + $('#message').val());  
                $('#message').val('').focus();  
                return false;  
            });  
        });  
    </script>  
</head>  
<body>  
<form id="send-message" class="form-inline">  
        <input id="name" type="text" value="name">  
        <input id="message" type="text" value="contain" />  
       &nbsp; <button class="btn btn-success" type="submit">Send</button>  
    </form>  
    <div id="messages"></div>  
</body>  
</html>