예제 #1
0
        // buffer: buffer for recv
        private WebSocket(ByteBuffer buffer, string url, List <string> protocols)
        {
            _url       = url;
            _buffer    = buffer;
            _protocols = protocols != null?protocols.ToArray() : new string[]
            {
                ""
            };

            _rwlock.EnterWriteLock();
            _websockets.Add(this);
            _rwlock.ExitWriteLock();

            do
            {
                if (_protocols != null && _protocols.Length > 0)
                {
                    _context = WSApi.ulws_create(_protocols[0], _callback, 1024 * 4, 1024 * 4);
                    if (_context.IsValid())
                    {
                        SetReadyState(ReadyState._CONSTRUCTED);
                        break;
                    }
                }
                SetReadyState(ReadyState.CLOSED);
            } while (false);
        }
예제 #2
0
        private void Update()
        {
            switch (_readyState)
            {
            case ReadyState.OPEN:
            case ReadyState.CLOSING:
            case ReadyState.CONNECTING:
                if (!_context.IsValid())
                {
                    return;
                }

                _is_polling = true;
                do
                {
                    _is_servicing = false;
                    WSApi.lws_service(_context, 0);
                } while (_is_servicing);
                _is_polling = false;
                break;

            case ReadyState._CONSTRUCTED:
                Connect();
                break;
            }

            if (_is_context_destroying)
            {
                Destroy();
            }
        }
예제 #3
0
        public JsonResult vdian_shop_cate_del(string id)
        {
            Class  c      = ClassService.instance().Single(new Guid(id));
            string result = WSApi.vdian_shop_cate_del(GetToken(), c.cate_id);
            string msg    = Utils.GetJsonValue(result, "status_reason");

            c.cate_id = "";
            ClassService.instance().Update(c);
            return(Json(msg, JsonRequestBehavior.AllowGet));
        }
예제 #4
0
 private void SetClose()
 {
     if (_wsi.IsValid())
     {
         _is_closing = true;
         SetReadyState(ReadyState.CLOSING);
         WSApi.lws_callback_on_writable(_wsi);
         _wsi = lws.Null;
     }
     else
     {
         SetReadyState(ReadyState.CLOSED);
     }
 }
예제 #5
0
        public JsonResult Product_onSale(string id)
        {
            Product p = ProductService.instance().Single(new Guid(id));

            p.opt = (p.opt == "1" ? "2" : "1");
            string result_msg = WSApi.vdian_item_onSale(GetToken(), p.itemid, p.opt);

            if (Utils.GetJsonValue(result_msg, "status_code") == "0")
            {
                ProductService.instance().Update(p);
            }

            return(Json(Utils.GetJsonValue(result_msg, "status_reason"), JsonRequestBehavior.AllowGet));
        }
예제 #6
0
        // return -1 if error
        private int OnReceive(IntPtr @in, size_t len)
        {
            if (WSApi.lws_is_first_fragment(_wsi) == 1)
            {
                _buffer.writerIndex = 0;
            }
            _buffer.WriteBytes(@in, len);

            if (WSApi.lws_is_final_fragment(_wsi) == 1)
            {
                var is_binary = WSApi.lws_frame_is_binary(_wsi) == 1;
                if (is_binary)
                {
                    unsafe
                    {
                        fixed(byte *ptr = _buffer.data)
                        {
                            var val = JSApi.JS_NewArrayBufferCopy(_jsContext, ptr, _buffer.writerIndex);

                            CallScript("onmessage", val);
                            JSApi.JS_FreeValue(_jsContext, val);
                        }
                    }
                }
                else
                {
                    unsafe
                    {
                        _buffer.WriteByte(0); // make it null terminated
                        fixed(byte *ptr = _buffer.data)
                        {
                            var val = JSApi.JS_NewString(_jsContext, ptr);

                            CallScript("onmessage", val);
                            JSApi.JS_FreeValue(_jsContext, val);
                        }
                    }
                }
            }

            return(0);
        }
예제 #7
0
        public JsonResult vdian_shop_cate_add(string id)
        {
            Class  c      = ClassService.instance().Single(new Guid(id));
            string result = WSApi.vdian_shop_cate_add(WSApiJson.vdian_shop_cate_add(GetToken(), c));
            string msg    = Utils.GetJsonValue(result, "status_reason");

            if (msg == "success")
            {
                string catesJson = WSApi.vdian_shop_cate_get(GetToken());
                catesJson = JsonHelper.GetJsonValue(catesJson, "result");
                List <cates_result> list  = JsonHelper.DeserializeJsonToList <cates_result>(catesJson);
                cates_result        cate_ = list.Find(m => m.cate_name == c.Title);
                if (cate_ != null)
                {
                    c.cate_id = cate_.cate_id;
                    ClassService.instance().Update(c);
                }
            }
            return(Json(msg, JsonRequestBehavior.AllowGet));
        }
예제 #8
0
        private void OnWrite()
        {
            if (_pending.Count > 0)
            {
                var packet   = _pending.Dequeue();
                var protocol = packet.is_binary ? lws_write_protocol.LWS_WRITE_BINARY : lws_write_protocol.LWS_WRITE_TEXT;
                var len      = packet.buffer.writerIndex - WSApi.LWS_PRE;

                unsafe
                {
                    fixed(byte *buf = packet.buffer.data)
                    {
                        WSApi.lws_write(_wsi, &buf[WSApi.LWS_PRE], len, protocol);
                    }
                }

                _bufferedAmount -= len;
                packet.Release();
                if (_pending.Count > 0)
                {
                    WSApi.lws_callback_on_writable(_wsi);
                }
            }
        }
예제 #9
0
        private static JSValue _js_send(JSContext ctx, JSValue this_obj, int argc, JSValue[] argv)
        {
            try
            {
                WebSocket self;
                if (!js_get_classvalue(ctx, this_obj, out self))
                {
                    throw new ThisBoundException();
                }
                if (argc == 0)
                {
                    throw new ParameterException("data", typeof(string), 0);
                }
                if (!self._wsi.IsValid() || !self._context.IsValid())
                {
                    return(JSApi.JS_ThrowInternalError(ctx, "websocket closed"));
                }

                if (argv[0].IsString())
                {
                    // send text data
                    size_t psize;
                    var    pointer = JSApi.JS_ToCStringLen(ctx, out psize, argv[0]);
                    if (pointer != IntPtr.Zero && psize > 0)
                    {
                        var buffer = ScriptEngine.AllocByteBuffer(ctx, psize + WSApi.LWS_PRE);
                        if (buffer != null)
                        {
                            buffer.WriteBytes(WSApi.LWS_PRE);
                            buffer.WriteBytes(pointer, psize);
                            self._pending.Enqueue(new Packet(false, buffer));
                            self._bufferedAmount += psize;
                            WSApi.lws_callback_on_writable(self._wsi);
                        }
                        else
                        {
                            JSApi.JS_FreeCString(ctx, pointer);
                            return(JSApi.JS_ThrowInternalError(ctx, "buf alloc failed"));
                        }
                    }
                    JSApi.JS_FreeCString(ctx, pointer);
                }
                else
                {
                    size_t psize;
                    var    pointer = JSApi.JS_GetArrayBuffer(ctx, out psize, argv[0]);
                    if (pointer != IntPtr.Zero)
                    {
                        var buffer = ScriptEngine.AllocByteBuffer(ctx, psize + WSApi.LWS_PRE);
                        if (buffer != null)
                        {
                            buffer.WriteBytes(WSApi.LWS_PRE);
                            buffer.WriteBytes(pointer, psize);
                            self._pending.Enqueue(new Packet(false, buffer));
                            self._bufferedAmount += psize;
                            WSApi.lws_callback_on_writable(self._wsi);
                        }
                        else
                        {
                            return(JSApi.JS_ThrowInternalError(ctx, "buf alloc failed"));
                        }
                    }
                    else
                    {
                        var asBuffer = JSApi.JS_GetProperty(ctx, argv[0], ScriptEngine.GetContext(ctx).GetAtom("buffer"));
                        if (asBuffer.IsObject())
                        {
                            pointer = JSApi.JS_GetArrayBuffer(ctx, out psize, asBuffer);
                            JSApi.JS_FreeValue(ctx, asBuffer);
                            if (pointer != IntPtr.Zero)
                            {
                                var buffer = ScriptEngine.AllocByteBuffer(ctx, psize + WSApi.LWS_PRE);
                                if (buffer != null)
                                {
                                    buffer.WriteBytes(WSApi.LWS_PRE);
                                    buffer.WriteBytes(pointer, psize);
                                    self._pending.Enqueue(new Packet(false, buffer));
                                    self._bufferedAmount += psize;
                                    WSApi.lws_callback_on_writable(self._wsi);
                                    return(JSApi.JS_UNDEFINED);
                                }
                                else
                                {
                                    return(JSApi.JS_ThrowInternalError(ctx, "buf alloc failed"));
                                }
                            }
                        }
                        else
                        {
                            JSApi.JS_FreeValue(ctx, asBuffer);
                        }
                        return(JSApi.JS_ThrowInternalError(ctx, "unknown buf type"));
                    }
                }

                return(JSApi.JS_UNDEFINED);
            }
            catch (Exception exception)
            {
                return(JSApi.ThrowException(ctx, exception));
            }
        }
예제 #10
0
        private async void Connect()
        {
            if (_readyState != ReadyState._CONSTRUCTED)
            {
                return;
            }
            SetReadyState(ReadyState._DNS);
            var uri            = new Uri(_url);
            var ssl_type       = uri.Scheme == "ws" ? ulws_ssl_type.ULWS_DEFAULT : ulws_ssl_type.ULWS_USE_SSL_ALLOW_SELFSIGNED;
            var protocol_names = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(string.Join(",", _protocols));
            var path           = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(uri.AbsolutePath);
            var host           = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(uri.DnsSafeHost);
            var port           = uri.Port;

            switch (uri.HostNameType)
            {
            case UriHostNameType.IPv4:
            case UriHostNameType.IPv6:
            {
                var address = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(uri.DnsSafeHost);
                SetReadyState(ReadyState.CONNECTING);
                unsafe
                {
                    fixed(byte *protocol_names_ptr = protocol_names)
                    fixed(byte *host_ptr    = host)
                    fixed(byte *address_ptr = address)
                    fixed(byte *path_ptr    = path)
                    {
                        WSApi.ulws_connect(_context, protocol_names_ptr, ssl_type, host_ptr, address_ptr, path_ptr, port);
                    }
                }
            }
            break;

            default:
            {
                var entry = await Dns.GetHostEntryAsync(uri.DnsSafeHost);

                if (_readyState != ReadyState._DNS)
                {
                    // already closed
                    return;
                }
                SetReadyState(ReadyState.CONNECTING);
                try
                {
                    var ipAddress = Select(entry.AddressList);
                    var address   = QuickJS.Utils.TextUtils.GetNullTerminatedBytes(ipAddress.ToString());
                    unsafe
                    {
                        fixed(byte *protocol_names_ptr = protocol_names)
                        fixed(byte *host_ptr    = host)
                        fixed(byte *address_ptr = address)
                        fixed(byte *path_ptr    = path)
                        {
                            WSApi.ulws_connect(_context, protocol_names_ptr, ssl_type, host_ptr, address_ptr, path_ptr, port);
                        }
                    }
                }
                catch (Exception exception)
                {
                    // UnityEngine.Debug.LogErrorFormat("{0}", exception);
                    SetReadyState(ReadyState.CLOSED);
                    OnError(exception);
                }
            }
            break;
            }
        }
예제 #11
0
        public static int _callback(lws wsi, lws_callback_reasons reason, IntPtr user, IntPtr @in, size_t len)
        {
            var context   = WSApi.lws_get_context(wsi);
            var websocket = GetWebSocket(context);

            if (websocket == null)
            {
                return(-1);
            }

            switch (reason)
            {
            case lws_callback_reasons.LWS_CALLBACK_CHANGE_MODE_POLL_FD:
            {
                return(0);
            }

            case lws_callback_reasons.LWS_CALLBACK_CLIENT_RECEIVE:
            {
                websocket._is_servicing = true;
                return(websocket.OnReceive(@in, len));
            }

            case lws_callback_reasons.LWS_CALLBACK_CLIENT_WRITEABLE:
            {
                websocket._is_servicing = true;
                if (websocket._is_closing)
                {
                    WSApi.lws_close_reason(wsi, lws_close_status.LWS_CLOSE_STATUS_NORMAL, "");
                    return(-1);
                }
                websocket.OnWrite();
                return(0);
            }

            case lws_callback_reasons.LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS:
            {
                return(0);
            }

            case lws_callback_reasons.LWS_CALLBACK_CLIENT_ESTABLISHED:
            {
                websocket._is_servicing = true;
                websocket._wsi          = wsi;
                websocket.OnConnect();         // _on_connect(websocket, lws_get_protocol(wsi)->name);
                return(0);
            }

            case lws_callback_reasons.LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
            {
                websocket._is_servicing = true;
                websocket.OnError(@in, len);
                websocket.Destroy();
                return(-1);
            }

            case lws_callback_reasons.LWS_CALLBACK_WS_PEER_INITIATED_CLOSE:
            {
                websocket._is_servicing = true;
                websocket.OnCloseRequest(@in, len);
                return(0);
            }

            case lws_callback_reasons.LWS_CALLBACK_CLIENT_CLOSED:
            {
                websocket.SetClose();         // _duk_lws_close(websocket);
                websocket.Destroy();
                websocket.OnClose();
                return(0);
            }

            default:
            {
                return(0);
            }
            }
        }
예제 #12
0
 public void Init()
 {
     instance = new WSApi();
 }
예제 #13
0
        private void Initialize()
        {
            #region [ http api ]
            httpapi = new HttpApi("http://localhost:3000");
            #endregion

            #region [ ws api ]
            wsapi = new WSApi <User, string>();

            wsapi.EventWSError += (s, e) =>
            {
                Console.WriteLine($"[wsapi] EventWSError code = {e.Value.Code}, message = {e.Value.Message}");
            };

            #region [ IWSBase events ]
            wsapi.Ws.EventConnectionChange += (s, e) =>
            {
                if (e.Value)
                {
                    Console.WriteLine($"[IWSBase] connected '{e.Value}', id = {wsapi.Ws.Id}");
                }
                else
                {
                    Console.WriteLine($"[IWSBase] disconnected");
                }
            };
            wsapi.Ws.EventSubscriptionError += (s, e) =>
            {
                Console.WriteLine($"[IWSBase] EventSubscriptionError event = {e.Value.Name}, error = {e.Value.Exception.Message}");
            };
            wsapi.Ws.EventNewSocketInstance += (s, e) =>
            {
                Console.WriteLine($"[IWSBase] EventNewSocketInstance");
            };
            wsapi.Ws.EventSend += (s, e) =>
            {
                var strData = e.Value.Data == null
                    ? "null"
                    : e.Value.Data.ToString();

                Console.WriteLine($"[IWSBase] EventSend event = {e.Value.Name}, data = {strData}");
            };
            wsapi.Ws.EventReceive += (s, e) =>
            {
                var strData = e.Value.Data == null
                    ? "null"
                    : e.Value.Data.ToString();

                Console.WriteLine($"[IWSBase] EventReceive event = {e.Value.Name}, data = {strData}");
            };
            #endregion

            #region [ HubClient events ]
            wsapi.Hub.EventReceive += (s, e) =>
            {
                Console.WriteLine($"[HubClient] EventReceive service = {e.Value.service}, event = {e.Value.eventName}");
            };
            wsapi.Hub.EventSubscribed += (s, e) =>
            {
                Console.WriteLine($"[HubClient] EventSubscribed service = {e.Value.service}, event = {e.Value.eventName}");
            };
            wsapi.Hub.EventSubscriptionError += (s, e) =>
            {
                Console.WriteLine($"[HubClient] EventSubscriptionException service = {e.Value.Request.service}, event = {e.Value.Request.eventName}, exception = {e.Value.Exception.Message}");
            };
            #endregion
            #endregion
        }
예제 #14
0
        public JsonResult Product_Async(string id)
        {
            Hashtable      hash  = new Hashtable();
            Guid           ID    = new Guid(id);
            List <Product> plist = ProductService.instance().GetProductByCid(ID).ToList();

            foreach (var p in plist)
            {
                if (string.IsNullOrEmpty(p.itemid))
                {
                    product_item entity = new product_item();
                    entity.item_name = Utils.DropHTML(p.Description);
                    entity.price     = p.Attr.First().price.Price.ToString();
                    entity.stock     = p.Attr.First().price.Stock.ToString();
                    entity.imgs      = new List <string>();
                    entity.cate_ids  = new List <string>()
                    {
                        ClassService.instance().Single(p.ClassID).cate_id
                    };
                    entity.skus          = new List <skus>();
                    entity.merchant_code = "";
                    foreach (var item in FilesService.instance().GetFilesByRelationID(p.ID))
                    {
                        string reulst_msg = WSApi.upload(GetToken(), item.FilePath);
                        if (Utils.GetJsonValue(reulst_msg, "status_code") == "0")
                        {
                            string imgurl = Utils.GetJsonValue(reulst_msg, "result");
                            if (imgurl.Split('?').Length > 0)
                            {
                                entity.imgs.Add(imgurl.Split('?')[0]);
                            }
                            else
                            {
                                entity.imgs.Add(imgurl);
                            }
                        }
                    }
                    foreach (var item in Product_AttService.GetAttsByPID(ID))
                    {
                        entity.skus.Add(new skus()
                        {
                            price             = item.price.Price.ToString(),
                            sku_merchant_code = "",
                            stock             = item.price.Stock.ToString(),
                            title             = item.key.Name + ":" + item.val.Value
                        });
                    }
                    ;
                    string json        = WSApiJson.vdian_item_add(entity);
                    string msg         = WSApi.vdian_item_add(GetToken(), json);
                    string status_code = Utils.GetJsonValue(msg, "status_code");
                    if (status_code == "0")
                    {
                        p.itemid = Utils.GetJsonValue(msg, "itemid");
                        p.opt    = "1";
                        ProductService.instance().Update(p);
                    }
                    else
                    {
                        hash[p.Title] = Utils.GetJsonValue(msg, "status_reason");
                    }
                }
            }
            return(Json(hash, JsonRequestBehavior.AllowGet));
        }
예제 #15
0
        private string GetToken()
        {
            WeShop m = WeShopService.instance().GetEneityByCompanyID(UserDateTicket.Company.ID);

            return(WSApi.GetToken(m.appkey, m.secret));
        }
예제 #16
0
        public JsonResult Product(FormCollection form)
        {
            ResultBase_form result = new ResultBase_form();
            Guid            ID     = new Guid(form["ID"]);
            Product         p      = ProductService.instance().Single(ID);

            if (!string.IsNullOrEmpty(p.itemid))
            {
                string del_msg = WSApi.vdian_item_delete(GetToken(), p.itemid);
                if (Utils.GetJsonValue(del_msg, "status_code") != "0")
                {
                    result.msg = Utils.GetJsonValue(del_msg, "status_reason");
                    return(Json(result, JsonRequestBehavior.AllowGet));
                }
            }
            product_item entity = new product_item();

            entity.item_name = form["Description"];
            entity.price     = form["Price"];
            entity.stock     = form["Stock"];
            entity.imgs      = new List <string>();
            entity.cate_ids  = new List <string>()
            {
                form["cate_ids"]
            };
            entity.skus          = new List <skus>();
            entity.merchant_code = "";
            foreach (var item in FilesService.instance().GetFilesByRelationID(ID))
            {
                string reulst_msg = WSApi.upload(GetToken(), item.FilePath);
                if (Utils.GetJsonValue(reulst_msg, "status_code") == "0")
                {
                    string imgurl = Utils.GetJsonValue(reulst_msg, "result");
                    if (imgurl.Split('?').Length > 0)
                    {
                        entity.imgs.Add(imgurl.Split('?')[0]);
                    }
                    else
                    {
                        entity.imgs.Add(imgurl);
                    }
                }
            }
            foreach (var item in Product_AttService.GetAttsByPID(ID))
            {
                entity.skus.Add(new skus()
                {
                    price             = item.price.Price.ToString(),
                    sku_merchant_code = "",
                    stock             = item.price.Stock.ToString(),
                    title             = item.key.Name + ":" + item.val.Value
                });
            }
            ;
            string json = WSApiJson.vdian_item_add(entity);
            string msg  = WSApi.vdian_item_add(GetToken(), json);

            result.status = Convert.ToInt32(Utils.GetJsonValue(msg, "status_code"));
            if (result.status == 0)
            {
                p.itemid = Utils.GetJsonValue(msg, "itemid");
                p.opt    = "1";
                ProductService.instance().Update(p);
            }
            result.msg       = result.status == 0 ? "操作成功" : "操作失败";
            result.ResultURL = "/WeShop/Product/" + p.ID;
            return(Json(result, JsonRequestBehavior.AllowGet));
        }