C# socket编程 使用fleck轻松实现对话 https://github.com/statianzo/Fleck

 class Program
    {

        static void Main(string[] args)
        {
            FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://0.0.0.0: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.txt");
             //创建一个文件流
             FileStream fs = new FileStream(path, FileMode.Create);
 
             //将byte数组写入文件中
             fs.Write(file, 0, file.Length);
            //所有流类型都要关闭流,否则会出现内存泄露问题
             fs.Close();
                };
            });


            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }
    }

  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>websocket client</title>
    <script type="text/javascript">
        var start = function () {
            var inc = document.getElementById('incomming');
            var wsImpl = window.WebSocket || window.MozWebSocket;
            var form = document.getElementById('sendForm');
            var input = document.getElementById('sendText');

            inc.innerHTML += "connecting to server ..<br/>";

            // create a new websocket and connect
            window.ws = new wsImpl('ws://localhost:7181/');

            // when data is comming from the server, this metod is called
            ws.onmessage = function (evt) {
                inc.innerHTML += evt.data + '<br/>';
            };

            // when the connection is established, this method is called
            ws.onopen = function () {
                inc.innerHTML += '.. connection open<br/>';
            };

            // when the connection is closed, this method is called
            ws.onclose = function () {
                inc.innerHTML += '.. connection closed<br/>';
            }

            form.addEventListener('submit', function (e) {
                e.preventDefault();
                var val = input.value;
                ws.send(val);
                input.value = "";
            });

        }
        window.onload = start;
    </script>
</head>
<body>
    <form id="sendForm">
        <input id="sendText" placeholder="Text to send" />
    </form>
    <pre id="incomming"></pre>
</body>
</html>

 //实现聊天窗口与文件发送

<!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");
        }
        //连接关闭后响应
        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>
</body>
</html>

  

 

转载于:https://www.cnblogs.com/ProDoctor/p/6434206.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值