python-websocket前后端实际项目应用

项目实例,数据和图片以json的格式传送到后端并保存
前端页面效果:
python-websocket前后端实际项目应用_第1张图片

废话不多说,上代码:
新建websocket.py文件作为服务端

import json

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):
    import base64
    message = eval(json.loads(message))
    messageCode = ''.join(message.get('picture').split(',')[1:])
    imagedata = base64.b64decode(messageCode)
    print(type(imagedata), imagedata)
    with open('1.jpg', "wb") as f:
        f.write(imagedata)
    print("Client(%d) said: %s" % (client['id'], message))


if __name__ == '__main__':
    PORT = 9001
    server = WebsocketServer(PORT, "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)
    server.run_forever()

前端代码(客户端)
新建register.html文件
注:前端页面使用的是微信官方公众号的小插件,相应的文件可到官网自行下载即可运行,找不到的可以留言找我要

DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="css/weui.css" type="text/css">
    <link rel="stylesheet" href="css/easyui.css" type="text/css">
    <script type="text/javascript" src="js/tool.js">script>
    <script type="text/javascript" src="js/jquery-3.3.1.js">script>
    <script type="text/javascript" src="js/jquery.tmpl.js">script>
    <script type="text/javascript" src="js/jquery.easyui.min.js">script>
    <script type="text/javascript" src="js/easyui-lang-zh_CN.js">script>

    <script type="text/javascript" src="js/ui_register.js">script>
    <meta charset="UTF-8">
    <title>register floortitle>
head>
<body>
<div class="page">
    <div class="weui-form">
        <div class="weui-form__text-area">
            <h2 class="weui-form__title">请填写信息注册楼层h2>
        div>
        <div class="weui-form__control-area">
            <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">姓名(Name)label>div>
                <div class="weui-cell__bd">
                    <input id="js_input_name" class="weui-input" placeholder="请输入您的姓名(Please input your name)"/>
                div>
            div>
            <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">楼层(Floor)label>div>
                <div class="weui-cell__bd">
                    <input id="js_input_floor" class="weui-input" placeholder="请输入楼层(Please input floor)"/>
                div>
                
                
                
                
            div>
        div>
    div>
div>

<div class="page">
    <div class="page__bd">
        <div class="weui-gallery" id="gallery">
            <span class="weui-gallery__img" id="galleryImg">span>
            <div class="weui-gallery__opr">
                <a href="javascript:" class="weui-gallery__del">
                    <i class="weui-icon-delete weui-icon_gallery-delete">i>
                a>
            div>
        div>
        <div class="weui-uploader__hd">
            <p class="weui-uploader__title">请上传您的图片,最多一张(Please upload your picture, at most one)p>
            <div id="pictureNumber" class="weui-uploader__info">0/1div>
        div>
        <div class="weui-uploader__bd">
            <div class="weui-uploader__file weui-uploader__file_status"
                    style="display:block;background-image:url(images/Otis.jpg)">div>
            <ul class="weui-uploader__files" id="uploaderFiles">




            ul>
            <div class="weui-uploader__input-box">
                <input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*"
                       multiple/>
            div>
        div>
        <div class="page__ft">
            
        div>
    div>
    <script type="text/javascript">
        $(function () {
            var tmpl = '
  • '
    , $gallery = $("#gallery"), $galleryImg = $("#galleryImg"), $uploaderInput = $("#uploaderInput"), $uploaderFiles = $("#uploaderFiles"); var pictureNumber = document.getElementById('pictureNumber'); $uploaderInput.on("change", function (e) { // var $d = $("#pictureNumber"); // $d.text = '1/1'; var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files; var file = files[0]; if (pictureNumber.innerText === '1/1'){ $.messager.alert("提示", "只能选择一张图片","info"); return } pictureNumber.innerText = '1/1'; console.log(window.URL,window.webkitURL,window.mozURL); console.log(files.length); if (url) { src = url.createObjectURL(file); } else { src = e.target.result; } console.log(src); $uploaderFiles.append($(tmpl.replace('#url#', src))); }); // uploaderFiles var index; //which picture $uploaderFiles.on("click", "li", function () { index = $(this).index(); $galleryImg.attr("style", this.getAttribute("style")); $gallery.fadeIn(100); }); $gallery.on("click", function () { $gallery.fadeOut(100); }); // delete the picture $(".weui-gallery__del").click(function () { $uploaderFiles.find("li").eq(index).remove(); pictureNumber.innerText = '0/1'; }); });
    script> div> <div class="weui-form__opr-area"> <a onclick="submit()" class="weui-btn weui-btn_primary weui-btn_disabled" href="javascript:" id="showTooltips" name="yes">确定a> div> <script type="text/javascript"> // judge the input box option is empty $(function () { var $userName = $('#js_input_name'); var $floor = $('#js_input_floor'); $floor.on('input', function () { if ($floor.val() === '') { $('#showTooltips').addClass('weui-btn_disabled') } else { if ($userName.val() === '' && $floor.val() === '') { // alert('user name is none, please input your name'); $('#showTooltips').addClass('weui-btn_disabled'); } else { $('#showTooltips').removeClass('weui-btn_disabled'); } } }); }); script> body> html>

    js
    新建ui_register.js文件

    //UI-related script
    
    function submit() {
        var sub = document.getElementById('showTooltips');
        var myPopup = document.getElementById('myPopup');
        var $userName = $('#js_input_name');
        var $floor = $('#js_input_floor');
        var reInt = /^\+?[1-9][0-9]*$/;
        if ($userName.val() === '' || $floor.val() === '') {
            alert('Name or floor is none,please enter the complete information');
            console.log('66666')
            // return
        }
        // alert('hello')
        if (reInt.test($floor.val()) === false) {
            alert('please input int number')
        } else {
            // alert('true')
        }
        // get dispatch server IP
        var ip_addr = document.location.hostname;
        window.WebSocket = window.WebSocket || window.MozWebSocket;
        ws = new WebSocket('ws://' + ip_addr + ':9001');  // 申请新的客户端
        var fileObj = document.getElementById("uploaderInput").files[0];
        console.log(fileObj);
        var reader = new FileReader(); // 文件
        reader.readAsDataURL(fileObj);
        // binary system
        // reader.readAsArrayBuffer(fileObj);
        // reader.readAsBinaryString(fileObj);
        reader.onload = function (e) {
            //read the result
            console.log('text/url/binary system/binary system string', reader.result);
            var imgurl = reader.result;
            document.getElementById('uploaderInput').src = imgurl;
            console.log(document.getElementById('uploaderInput').src = imgurl, imgurl);
            var imgBase64Data = e.target.result;
            // var head = imgBase64Data.indexOf("4") + 2;
            imgBase64Data = imgBase64Data.substring();
            // var reg = RegExp("\\+", "g");
            // imgBase64Data = imgBase64Data.replace(reg, "%2B");
            // console.log(imgBase64Data)
            var message = {
                userName: $userName.val(),
                floor: $floor.val(),
                picture: imgBase64Data
            };
            // You can send message to the Web Socket using ws.send.
            message = JSON.stringify(message);
            imgBase64Data = JSON.stringify(message);
            ws.addEventListener('open', function () {
                // ws.send(message)
                ws.send(imgBase64Data)
            });
        };
        // output("send: " + fileobj);
    }
    

    目录自行创建好之后:
    1.先启动websocket.py服务端
    2.打开客户端
    3.输入相应的信息,上传图片
    4.完成

    你可能感兴趣的:(python,前端,python,websocket,前端)