Home  >  Article  >  Backend Development  >  PHP websocket upload image problem

PHP websocket upload image problem

WBOY
WBOYOriginal
2016-08-04 09:21:241651browse

Now I am going to upload images via websocket and I have learned the following points:
1 Listening: First, a process must be suspended to listen for requests from the client
2 Handshake: For the first legal request, send a legal header back
3 Keep Connection: Broadcast when new messages arrive. Until the client disconnects
4 accept another request and repeat 2 and 3
But I am still confused about file upload, please give me a better understanding method.

Reply content:

Now I am going to upload images via websocket and I have learned the following points:
1 Listening: First, a process must be suspended to listen for requests from the client
2 Handshake: For the first legal request, send a legal header back
3 Keep Connection: Broadcast when new messages arrive. Until the client disconnects
4 accept another request and repeat 2 and 3
But I am still confused about file upload, please give me a better understanding method.

Post your own solution for your reference. If there are any shortcomings, I hope you can give me some pointers.
I am using the php swoole framework link http://www.swoole.com/ and the php part of HTML5 WebSocket
dome
server .php I use the swoole framework root directory/examples/websocket/server.php for editing
The most important $server->onMessage part of the code

<code>$server->on('message', function (swoole_websocket_server $_server, $frame) {
    $update_path = 'uploads/';   
    $data = json_decode($frame->data, 1);
    $exe = str_replace('/', '.', strstr(strstr($data['data'], ';', TRUE), '/'));
    $exe = $exe == '.jpeg' ? '.jpg' : $exe;
    $tmp = base64_decode(substr(strstr($data['data'], ','), 1));
    $path = $update_path . md5(rand(1000, 999)) . $exe;
    file_put_contents($path, $tmp);
    echo "image path : {$path}\n";
});</code>

Returns an uploaded image path
html part websocket.html

<code><!DOCTYPE html>
<html>
    <head>
        <title>WebSocket Chat Client</title>
        <meta charset="utf-8" />
        <script type="text/javascript" src="tmp/jquery/jquery-2.1.1.min.js"></script>
        <script type="text/javascript" >
            //判读浏览器是否支持websocket
            $().ready(function () {
                if (!window.WebSocket) {
                    alert("你的浏览器不支持该功能啊");
                }
            });
            //在消息框中打印内容
            function log(text) {
                $("#msg_paler").append("<li style='width:1120px;word-wrap:break-word;'>" + text + "</li>");
            }
            //请求的IP地址
            var wsServer = 'ws://192.168.0.123:9501/swoole/examples/websocket';
            var websocket = new WebSocket(wsServer);
            //连接成功建立后响应
            websocket.onopen = function (evt) {
                log("Connected to WebSocket server.");
            };

            websocket.onclose = function (evt) {
                log("Disconnected");
            };

            websocket.onmessage = function (evt) {
                log('Retrieved data from server: ' + evt.data);
            };

            websocket.onerror = function (evt, e) {
                log('Error occured: ' + evt.data);
            };

            $(function () {
                //发送base64格式的图片
                $("#sendFileForm").submit(function () {
                    var file = document.getElementById("file").files[0];
                    if (!/image\/\w+/.test(file.type)) {
                        log("请上传图片!");
                        return false;
                    }
                    var reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = function (e) {
                    var img_data = '{"type":"3","data":"' + this.result + '"}';
                        log("\n开始发送文件");
                        websocket.send(img_data);
                    }
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <h3>发送图片</h3>
        <div>
        <form id="sendFileForm">
            <input id="file" type="file" multiple />
            <input type="submit" value="Send" />
        </form>
        </div>
        <ul id="msg_paler"></ul>
        <br>
    </body>
</html></code>

This is the code for testing now
First open some terminal running tools such as Xshell, find the PHP file of the socket to be run and use the command
PHP websocket upload image problem
Then open websocket.html through the browser
If successful, it will return
PHP websocket upload image problem
Choose a picture Upload
View in the browserPHP websocket upload image problem
Display on the terminalPHP websocket upload image problemThen go to the folder you uploaded to see the uploaded filePHP websocket upload image problem
Just upload the image

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn