C# websocket與html js實現文件發送與接收處理

複製代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fleck;
using System.Threading;
using System.IO;
using System.Net.WebSockets;
using System.Net.Sockets;
using System.Net;
namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://192.168.31.37:7181");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                };
                socket.OnBinary = file =>
                {
                    string path = ("D:/test.jpg");
                    //建立一個文件流
                    FileStream fs = new FileStream(path, FileMode.Create);
                    //將byte數組寫入文件中
                    fs.Write(file, 0, file.Length);
                    //全部流類型都要關閉流,不然會出現內存泄露問題
                    fs.Close();
                };
            });

            //string ss = Console.ReadLine();
            var input = File.Open("D://test.jpg",FileMode.Open);
            while (true)
            {
                Thread.Sleep(2000);
                byte[] s = new byte[input.Length];
                input.Read(s, 0, s.Length);
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(s);
                }
                input.Close();
              input = File.Open("D://test.jpg", FileMode.Open);
            }
        }
    }
}
複製代碼
複製代碼
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat Client</title>
<meta charset="utf-8" />
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" >
    //判讀瀏覽器是否支持websocket
    $().ready(function() {
        if ( !window.WebSocket ) {
             alert("童鞋, 你的瀏覽器不支持該功能啊");
        }
         
    });
    
    //在消息框中打印內容
function log(text) {
        $("#log").append(text+"\n");
    }
    
    //全局的websocket變量
var ws;
    
    //建立鏈接
    $(function() {
    $("#uriForm").submit(function() {
        log("準備鏈接到" + $("#uri").val());
        
        ws = new WebSocket($("#uri").val());
        //鏈接成功創建後響應
        ws.onopen = function() {
            log("成功鏈接到" + $("#uri").val());
        }
        //收到服務器消息後響應
        ws.onmessage = function(e) {
            //log("收到服務器消息:" + e.data + "'\n");
             var reader = new FileReader();
             reader.onload=function(eve){
                        //判斷文件是否讀取完成
                         if(eve.target.readyState==FileReader.DONE)
                         {
//讀取文件完成後,建立img標籤來顯示服務端傳來的字節數//組
                            var img =document.createElement("img");
                //讀取文件完成後內容放在this===當前
//fileReader對象的result屬性中,將該內容賦值img標籤//瀏覽器就能夠自動解析內容格式而且渲染在瀏覽器中
                            img.src=this.result;
                        //將標籤添加到id爲show的div中不然,即使是有img也看不見
                            document.getElementById("show").appendChild(img);
                         }
                     };
                //調用FileReader的readAsDataURL的方法自動就會觸發onload事件
                     reader.readAsDataURL(e.data);

        }
        //鏈接關閉後響應
        ws.onclose = function() {
            log("關閉鏈接");
            $("#disconnect").attr({"disabled":"disabled"});
            $("#uri").removeAttr("disabled");
            $("#connect").removeAttr("disabled");
            ws = null;
        }
        $("#uri").attr({"disabled":"disabled"});
        $("#connect").attr({"disabled":"disabled"});
        $("#disconnect").removeAttr("disabled");
        return false;
    });
    });
    
    //發送字符串消息
    $(function() {
    $("#sendForm").submit(function() {
         if (ws) {
             var textField = $("#textField");
             ws.send(textField.val());
             log("我說:" + textField.val());
             textField.val("");
             textField.focus();
         }
         return false;
    });
    });
    
    //發送arraybuffer(二進制文件)
    $(function() {
    $("#sendFileForm").submit(function() {
        var inputElement = document.getElementById("file");
        var fileList = inputElement.files;
        
        for ( var i = 0; i < fileList.length; i++) {
            console.log(fileList[i]);
            log(fileList[i].name);
            //發送文件名
            ws.send(fileList[i].name);
//            reader.readAsBinaryString(fileList[i]);
//讀取文件  
       var reader = new FileReader();
            reader.readAsArrayBuffer(fileList[i]);
//            reader.readAsText(fileList[i]);
//文件讀取完畢後該函數響應
            reader.onload = function loaded(evt) {
                var binaryString = evt.target.result;
                // Handle UTF-16 file dump
                log("\n開始發送文件");
                ws.send(binaryString);
            }
        }
        return false;
    });
    });
    
    $(function() {
    $("#disconnect").click(function() {
         if (ws) {
             $("#log").empty();
             ws.close();
             ws = null;
         }
         return false;
    });
    });
    
    $(function() {
    $("#reset").click(function() {
        $("#log").empty();
         return false;
    });
    });
    
    
</script>
</head>
<body>
    <form id="uriForm">
        <input type="text" id="uri" value="ws://192.168.31.37:7181"
            style="width: 200px;"> <input type="submit" id="connect"
            value="Connect"><input type="button" id="disconnect"
            value="Disconnect" disabled="disabled">
    </form>
    <br>
    
    <form id="sendFileForm">
        <input id="file" type="file" multiple />
        <input type="submit" value="Send" />
        <input type="button" id="reset" value="清空消息框"/>
    </form>
    <br>
    <form id="sendForm">
        <input type="text" id="textField" value="" style="width: 200px;">
        <input type="submit" value="Send">
    </form>
    <br>
    <form>
        <textarea id="log" rows="30" cols="100"
            style="font-family: monospace; color: red;"></textarea>
    </form>
    <br>
<div id='show'></div>
</body>
</html>
複製代碼
相關文章
相關標籤/搜索