Exemplo n.º 1
0
        public String2 ReadFile(String filepath)
        {
            FileInfo info = new FileInfo(filepath);

            if (!info.Exists)
            {
                State        = "403";
                StateComment = "Not Found";
                return(_body);
            }
            if (".JS".Equals(info.Extension.ToUpper()))
            {
                ContextType = "text/javascript; charset=UTF-8";
            }
            if (".CSS".Equals(info.Extension.ToUpper()))
            {
                ContextType = "text/css; charset=UTF-8";
            }
            using (FileStream stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read))
            {
                _body = new String2((int)info.Length);
                stream.Read(_body.ToBytes(), 0, (int)info.Length);
            }
            StateOK();
            return(_body);
        }
Exemplo n.º 2
0
 public void ServerStart()
 {
     ThreadPool.QueueUserWorkItem((c) =>
     {
         while (true)
         {
             Socket client = null;
             try
             {
                 client = Accept();
                 ThreadPool.QueueUserWorkItem((temp_client) =>
                 {
                     var _client    = temp_client as Socket;
                     String2 buffer = new String2(Define.BUFFER_SIZE);
                     _client.Receive(buffer.ToBytes(), buffer.Length, SocketFlags.None);
                     if (buffer.IsEmpty())
                     {
                         logger.Debug("not Byte data..");
                         //TODO : Bug??
                         _client.Close();
                         return;
                     }
                     Request req = new Request(buffer);
                     Console.WriteLine(req.Uri);
                     if (req.IsWebSocket())
                     {
                         socketlist.Add(new WebSocket(client, this, req, _websocket_method_list));
                         return;
                     }
                     Response res = new Response();
                     Console.WriteLine(req.Uri);
                     if (_method_list.ContainsKey(req.Uri))
                     {
                         _method_list[req.Uri](req, res);
                     }
                     else if (_rootpath != null)
                     {
                         string filepath = _rootpath + req.Uri.ToString();
                         if (File.Exists(filepath))
                         {
                             res.ReadFile(filepath);
                         }
                     }
                     String2 sendbuffer = TransResponse(res);
                     client.Send(sendbuffer.ToBytes(), sendbuffer.Length, SocketFlags.None);
                     _client.Close();
                 }, client);
             }
             catch (Exception e)
             {
                 if (client != null)
                 {
                     client.Dispose();
                 }
                 throw e;
             }
         }
     });
 }
Exemplo n.º 3
0
        public WebSocket(Socket socket, Server server, Request req, Func <String2, WebSocketNode> method)
        {
            this._socket = socket;
            this._header = req;
            this._method = method;
            this._server = server;
            String2 rvheader = Handshake(req.Header["Sec-WebSocket-Key"]);

            socket.Send(rvheader.ToBytes(), rvheader.Length, SocketFlags.None);
            Listen();
        }
Exemplo n.º 4
0
        public WebSocket(Socket socket, Server server, Request req, Func <String2, Opcode, WebSocketNode> method)
        {
            this._socket = socket;
            this._header = req;
            this._method = method;
            this._server = server;
            logger       = LoggerBuilder.Init().Set(this.GetType());
            String2 rvheader = Handshake(req.Headers["Sec-WebSocket-Key"]);

            socket.Send(rvheader.ToBytes(), rvheader.Length, SocketFlags.None);
            Listen();
        }
Exemplo n.º 5
0
        private String2 ReadFile(String path)
        {
            FileInfo info = new FileInfo(path);

            if (!info.Exists)
            {
                return(null);
            }
            String2 temp = new String2((int)info.Length);

            using (FileStream stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read))
            {
                stream.Read(temp.ToBytes(), 0, temp.Length);
            }
            return(temp);
        }
Exemplo n.º 6
0
 public void SetZip(String file)
 {
     using (ZipFile zip = new ZipFile(file))
     {
         foreach (var z in zip)
         {
             using (var reader = z.OpenReader())
             {
                 int     length = (int)reader.Length;
                 String2 temp   = new String2(length);
                 reader.Read(temp.ToBytes(), 0, length);
                 String2 f = z.FileName.Replace("\\", "/");
                 this.zipmap.Add("/" + f, temp);
             }
         }
     }
 }
Exemplo n.º 7
0
        private void SendWorkTemp(IWorkSocketClient client, String file, String title)
        {
            WebSocketMessageBuilder builder = WebSocketMessageBuilder.GetMessage(MessageType.WORKTEMP);
            FileInfo info = new FileInfo(Program.WORK_PATH + Path.DirectorySeparatorChar + file);
            String2  data = new String2((int)info.Length, Encoding.UTF8);

            using (FileStream stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read))
            {
                stream.Read(data.ToBytes(), 0, data.Length);
                //data = String2.ReadStream(stream, Encoding.UTF8, (int)info.Length);
            }
            builder.SetWorkTitle(title);
            builder.SetMessage(data.ToString());
            String2 message = builder.Build();

            client.Send((int)Opcode.BINARY, message);
        }
Exemplo n.º 8
0
 public void Send(int opcode, String2 data)
 {
     try
     {
         if ((opcode == (int)Opcode.MESSAGE) || (opcode == (int)Opcode.BINARY) && data != null)
         {
             if (data.Length <= 0x80)
             {
                 _socket.Send(new byte[] { (byte)(0x80 | 1), (byte)data.Length });
             }
             else if (data.Length <= 65535)
             {
                 _socket.Send(new byte[] { (byte)(0x80 | 1), (byte)0x7E });
                 _socket.Send(Reverse(BitConverter.GetBytes((short)data.Length)));
             }
             else
             {
                 _socket.Send(new byte[] { (byte)(0x80 | 1), (byte)0x7F });
                 _socket.Send(Reverse(BitConverter.GetBytes((long)data.Length)));
             }
             _socket.Send(data.ToBytes(), data.Length, SocketFlags.None);
             return;
         }
         else if ((opcode == (int)Opcode.PING) || (opcode == (int)Opcode.PONG))
         {
             _socket.Send(new byte[] { (byte)(0x80 | opcode), (byte)0x00 });
             return;
         }
         throw new Exception("This setting is wrong OPCODE = " + opcode);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         _socket.Close();
         _server.RemoveWebSocket(this);
     }
 }
Exemplo n.º 9
0
        public void ServerStart()
        {
            ThreadPool.QueueUserWorkItem((c) =>
            {
                while (true)
                {
                    Socket client = null;
                    try
                    {
                        client = Accept();
                        ThreadPool.QueueUserWorkItem((temp_client) =>
                        {
                            var _client = temp_client as Socket;
                            try
                            {
                                String2 buffer = new String2(Define.BUFFER_SIZE);
                                _client.Receive(buffer.ToBytes(), buffer.Length, SocketFlags.None);
                                if (buffer.IsEmpty())
                                {
                                    _client.Close();
                                    return;
                                }
                                Request req = new Request(this, buffer);
                                if (req.IsWebSocket())
                                {
                                    socketlist.Add(new WebSocket(client, this, req, _websocket_method_list));
                                    return;
                                }
                                Response res = new Response(this, req);
                                String2 url  = req.Uri;
                                if (_default != null && url.ToString().Equals("/"))
                                {
                                    url += _default;
                                }

                                if (_method_list.ContainsKey(url))
                                {
                                    _method_list[url](req, res);
                                }
                                else if (zipmap.ContainsKey(url))
                                {
                                    String extension = url.SubString(url.Length - 4, 4).ToUpper().ToString();
                                    if (".JS".Equals(extension.Substring(1)))
                                    {
                                        res.ContextType = "text/javascript; charset=UTF-8";
                                    }
                                    else if (".CSS".Equals(extension))
                                    {
                                        res.ContextType = "text/css; charset=UTF-8";
                                    }
                                    res.Body = zipmap[url];
                                }
                                else if (_rootpath != null)
                                {
                                    string filepath = _rootpath + url.ToString();
                                    if (File.Exists(filepath))
                                    {
                                        res.ReadFile(filepath);
                                    }
                                }
                                String2 sendbuffer = res.View();
                                client.Send(sendbuffer.ToBytes(), sendbuffer.Length, SocketFlags.None);
                                ThreadPool.QueueUserWorkItem((_) =>
                                {
                                    Thread.Sleep(5000);
                                    _client.Close();
                                });
                            }
                            catch (Exception e)
                            {
                                if (_client != null)
                                {
                                    _client.Dispose();
                                }
                                Console.WriteLine(e);
                            }
                        }, client);
                    }
                    catch (Exception e)
                    {
                        if (client != null)
                        {
                            client.Dispose();
                        }
                        Console.WriteLine(e);
                    }
                }
            });
        }
Exemplo n.º 10
0
 public Action <IWorkSocketClient, byte, String2> SetReceive()
 {
     return((client, opcode, data) =>
     {
         if (file.Open && opcode != (int)Opcode.BINARY)
         {
             file.Init();
         }
         if (opcode == (int)Opcode.MESSAGE)
         {
             MessageNode message = MessageDirector.Instance().GetNodeFromJson(data);
             if (message.MessageType == MessageType.MESSAGE)
             {
                 MessageNode sendMessage = MessageDirector.Instance().CreateNode();
                 sendMessage.MessageType = MessageType.MESSAGE;
                 sendMessage.Message = client.SocketClient.RemoteEndPoint + "-" + message.Message;
                 String2 json = MessageDirector.Instance().GetJsonFromNode(sendMessage);
                 SendBroadcast(MessageType.MESSAGE, json);
                 Console.WriteLine(sendMessage.Message);
             }
             else if (message.MessageType == MessageType.WORKTEMP)
             {
                 FileInfo info = new FileInfo(Program.WORK_PATH + Path.DirectorySeparatorChar + message.WorkTitle);
                 String2 buffer = new String2(message.Message, Encoding.UTF8);
                 using (FileStream stream = new FileStream(info.FullName, FileMode.Create, FileAccess.Write))
                 {
                     stream.Write(buffer.ToBytes(), 0, buffer.Length);
                 }
                 SendWorkList(client, WorkType.WorkListNotice);
             }
             else if (message.MessageType == MessageType.WORKNOTICE)
             {
                 String buffer = message.Message;
                 SendWorkTemp(client, buffer.Trim(), buffer.Trim());
             }
         }
         if (opcode == (int)Opcode.BINARY)
         {
             if (data.Length < 1)
             {
                 //logger.Error("It is being have downloading.but because what the data is nothing is stopped.");
                 //continue;
             }
             byte type = data[0];
             if (type == (byte)FileMessageType.FileOpen)
             {
                 file.Length = BitConverter.ToInt32(data.ToBytes(), 1);
                 String2 filename = data.SubString(5, data.Length - 5);
                 filename.Encode = Encoding.UTF8;
                 //logger.Info("filename - " + filename);
                 file.SetStream(new FileStream(Program.FILE_STORE_PATH + filename.Trim().ToString(), FileMode.Create, FileAccess.Write), file.Length);
                 return;
             }
             if (type == (byte)FileMessageType.FileWrite)
             {
                 if (!file.Open)
                 {
                     //logger.Error("It is being have downloading.but because what file's connection is closed.");
                     file.Init();
                     return;
                 }
                 String2 binary = data.SubString(1, data.Length - 1);
                 file.StreamBuffer.Write(binary.ToBytes(), 0, binary.Length);
                 file.Peek += binary.Length;
                 //logger.Info(file.Peek);
                 if (file.Peek >= file.Length)
                 {
                     file.Complete();
                     client.Send((int)Opcode.BINARY, new String2("File upload Success!!", Encoding.UTF8));
                 }
                 return;
             }
             if (type == (byte)FileMessageType.FileSearch || type == (byte)FileMessageType.FileListNotice)
             {
                 SendFileList(client, (FileMessageType)type);
                 return;
             }
             if (type == (byte)WorkType.WorkSearch || type == (byte)WorkType.WorkListNotice)
             {
                 SendWorkList(client, (WorkType)type);
             }
             //logger.Error("FileMessage type is wrong.");
             file.Init();
         }
     });
 }
Exemplo n.º 11
0
        public static void Run(IWorkSocketClient client, byte opcode, String2 data)
        {
            SendWorkTemp(client, "default", DateTime.Now.ToString("yyyy_MM_dd") + "_業務報告");
            SendFileList(client, FileMessageType.FileSearch);
            SendWorkList(client, WorkType.WorkSearch);

            if (file.Open && opcode != (int)Opcode.BINARY)
            {
                //logger.Error("It's error what transfer the file.");
                file.Init();
            }
            if (opcode == (int)Opcode.MESSAGE)
            {
                IDictionary <String, String> messageBuffer = JsonConvert.DeserializeObject <Dictionary <String, String> >(data.ToString());
                if (String.Equals(messageBuffer["TYPE"], "1"))
                {
                    WebSocketMessageBuilder builder = WebSocketMessageBuilder.GetMessage(MessageType.MESSAGE);
                    String chatMessage = client.SocketClient.RemoteEndPoint + "-" + messageBuffer["MESSAGE"];
                    builder.SetMessage(chatMessage);
                    String2 message = builder.Build();
                    Console.WriteLine(message);

                    /*foreach (WebSocketServer client1 in clientlist)
                     * {
                     *  client1.Send((int)OPCODE.MESSAGE, message);
                     * }*/
                    //logger.Info(message);
                }
                else if (String.Equals(messageBuffer["TYPE"], "4"))
                {
                    FileInfo info  = new FileInfo(Program.WORK_PATH + Path.DirectorySeparatorChar + messageBuffer["WORKTITLE"]);
                    String2  data1 = new String2(messageBuffer["MESSAGE"], Encoding.UTF8);
                    using (FileStream stream = new FileStream(info.FullName, FileMode.Create, FileAccess.Write))
                    {
                        //data1.WriteStream(stream);
                        stream.Write(data1.ToBytes(), 0, data1.Length);
                    }
                    SendWorkList(client, WorkType.WorkListNotice);
                }
                else if (String.Equals(messageBuffer["TYPE"], "5"))
                {
                    String data1 = messageBuffer["MESSAGE"];
                    SendWorkTemp(client, data1.Trim(), data1.Trim());
                }
            }
            if (opcode == (int)Opcode.BINARY)
            {
                if (data.Length < 1)
                {
                    //logger.Error("It is being have downloading.but because what the data is nothing is stopped.");
                    //continue;
                }
                byte type = data[0];
                if (type == (byte)FileMessageType.FileOpen)
                {
                    file.Length = BitConverter.ToInt32(data.ToBytes(), 1);
                    String2 filename = data.SubString(5, data.Length - 5);
                    filename.Encode = Encoding.UTF8;
                    //logger.Info("filename - " + filename);
                    file.SetStream(new FileStream(Program.FILE_STORE_PATH + filename.Trim().ToString(), FileMode.Create, FileAccess.Write), file.Length);
                    //continue;
                }
                if (type == (byte)FileMessageType.FileWrite)
                {
                    if (!file.Open)
                    {
                        //logger.Error("It is being have downloading.but because what file's connection is closed.");
                        file.Init();
                        //continue;
                    }
                    String2 binary = data.SubString(1, data.Length - 1);
                    file.StreamBuffer.Write(binary.ToBytes(), 0, binary.Length);
                    file.Peek += binary.Length;
                    //logger.Info(file.Peek);
                    if (file.Peek >= file.Length)
                    {
                        file.Complete();
                        client.Send((int)Opcode.BINARY, new String2("File upload Success!!", Encoding.UTF8));
                    }
                    //continue;
                }
                if (type == (byte)FileMessageType.FileSearch || type == (byte)FileMessageType.FileListNotice)
                {
                    SendFileList(client, (FileMessageType)type);
                    //continue;
                }
                if (type == (byte)WorkType.WorkSearch || type == (byte)WorkType.WorkListNotice)
                {
                    SendWorkList(client, (WorkType)type);
                }
                //logger.Error("FileMessage type is wrong.");
                file.Init();
            }
        }