Exemplo n.º 1
0
 public void Send(byte[] data, int offset, int count)
 {
     if (InternalSocket.Connected)
     {
         InternalSocket.Send(data, offset, count, SocketFlags.None);
     }
 }
Exemplo n.º 2
0
 public void BeginReceive(ISocketObject listener = null)
 {
     if (InternalSocket.Connected)
     {
         InternalSocket.BeginReceive(_ReceiveBuffer, 0, _ReceiveBuffer.Length, SocketFlags.None, ReceiveCallback, listener ?? this);
     }
 }
Exemplo n.º 3
0
 public void BeginSend(byte[] data, int offset, int count)
 {
     if (InternalSocket.Connected)
     {
         InternalSocket.BeginSend(data, offset, count, SocketFlags.None, SendCallback, this);
     }
 }
Exemplo n.º 4
0
        private void EndAccepting(IAsyncResult result)
        {
            var client = new Client(InternalSocket.EndAccept(result));

            client.StartReceive();
            InternalSocket.BeginAccept(EndAccepting, null);
        }
Exemplo n.º 5
0
        public void Connect(IPAddress hostname, int port)
        {
            var sw = Stopwatch.StartNew();

            try
            {
                //Caused by: java.net.SocketTimeoutException: Connection timed out
                //       at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
                //       at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:357)
                //       at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
                //       at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
                //       at java.net.Socket.connect(Socket.java:1002)
                //       at java.net.Socket.connect(Socket.java:945)
                //       at ScriptCoreLibJava.BCLImplementation.System.Net.Sockets.__TcpClient.Connect(__TcpClient.java:96)

                InternalSocket.setSoTimeout(150000);

                InternalSocket.connect(new java.net.InetSocketAddress(((__IPAddress)(object)hostname).InternalAddress, port));
            }
            catch
            {
                Console.WriteLine("Connect fault " + new { hostname, port, sw.ElapsedMilliseconds });

                throw;
            }
        }
Exemplo n.º 6
0
 public void Disconnect()
 {
     if (InternalSocket.Connected)
     {
         InternalSocket.Disconnect(false);
     }
 }
Exemplo n.º 7
0
        public void Listen(IPEndPoint hostEndPoint)
        {
            InternalSocket.Bind(hostEndPoint);

            InternalSocket.Listen(100);

            InternalSocket.BeginAccept(AcceptCallback, this);
        }
Exemplo n.º 8
0
        public void Listen(int port)
        {
            InternalSocket.Bind(new IPEndPoint(IPAddress.Any, port));

            InternalSocket.Listen(100);

            InternalSocket.BeginAccept(AcceptCallback, this);
        }
Exemplo n.º 9
0
        public void Connect(IPAddress address, int port)
        {
            InternalSocket.Connect(address, port);

            Address = address;
            Port    = port;

            BeginReceive();
        }
        public Task <bool> Connect(SocketCreationContext socketConnectionContext)
        {
            if (InternalSocket.State == WebSocketState.Connecting || InternalSocket.State == WebSocketState.Open)
            {
                return(Task.FromResult(true));
            }

            return(InternalSocket.ConnectAsync(socketConnectionContext));
        }
Exemplo n.º 11
0
 public void Close()
 {
     try
     {
         InternalSocket.close();
     }
     catch
     {
         throw new InvalidOperationException();
     }
 }
Exemplo n.º 12
0
 public void Connect(string hostname, int port)
 {
     try
     {
         InternalSocket.connect(new java.net.InetSocketAddress(hostname, port));
     }
     catch
     {
         throw;
     }
 }
        public int available()
        {
            //WebGL should not do this, that's why it's optional
            //however the non-webgl Websockets implementation HAS TO.
            if (ReceiveOnAvailableCheck)
            {
                InternalSocket.Receive();
            }

            lock (SyncObj)
                return((int)PendingBytes);
        }
Exemplo n.º 14
0
        private void AcceptCallback(IAsyncResult ar)
        {
            var socketObject = new SocketObject(InternalSocket.EndAccept(ar));

            if (SocketConnected != null)
            {
                SocketConnected(socketObject);
            }

            socketObject.BeginReceive(this);

            InternalSocket.BeginAccept(AcceptCallback, this);
        }
Exemplo n.º 15
0
 protected virtual void Dispose(bool disposing)
 {
     if (_disposed)
     {
         return;
     }
     if (disposing)
     {
         if (this._socket != null)
         {
             this._socket.Dispose();
             this._socket = null;
         }
     }
     _disposed = true;
 }
Exemplo n.º 16
0
        public void Start()
        {
            try
            {
                InternalSocket.Bind(ServerEndPoint);
                InternalSocket.Listen(500);
                InternalSocket.BeginAccept(EndAccepting, null);
            }
            catch (SocketException ex)
            {
                if (ex.ErrorCode == (int)SocketError.AddressAlreadyInUse)
                {
                    throw new InvalidOperationException("The selected port is already used by another process");
                }

                throw new NotSupportedException("oops unexpected error was thrown please report this issue to the developer.");
            }
        }
Exemplo n.º 17
0
        private void InternalGetNetworkStream()
        {
            try
            {
                // http://stackoverflow.com/questions/7297173/android-outputstreamwriter-didnt-send-the-data-after-flush-socket



                CachedGetStream = (NetworkStream)(object)new __NetworkStream
                {
                    InternalInputStream  = InternalSocket.getInputStream(),
                    InternalOutputStream = InternalSocket.getOutputStream()
                };
            }
            catch
            {
                throw;
            }
        }
Exemplo n.º 18
0
 private void Disconnect()
 {
     if (_socket != null)
     {
         try
         {
             _socket.Dispose();
             _socket = null;
             _closed = true;
         }
         catch (Exception ex)
         {
             if (this.OnError != null)
             {
                 this.OnError(this, ex);
             }
         }
     }
 }
Exemplo n.º 19
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            var owner = ar.AsyncState as SocketObject;

            var count = 0;

            try
            {
                count = InternalSocket.EndReceive(ar);
            }
            catch (Exception)
            {
                if (owner.SocketDisconnected != null)
                {
                    owner.SocketDisconnected.Invoke(this);
                }

                Dispose();
                return;
            }

            if (count == 0)
            {
                if (owner.SocketDisconnected != null)
                {
                    owner.SocketDisconnected.Invoke(this);
                }

                Dispose();
                return;
            }

            if (owner.ReceivedData != null)
            {
                owner.ReceivedData.Invoke(this, _ReceiveBuffer, 0, count);
            }

            if (InternalSocket.Connected)
            {
                InternalSocket.BeginReceive(_ReceiveBuffer, 0, _ReceiveBuffer.Length, SocketFlags.None, ReceiveCallback, ar.AsyncState);
            }
        }
Exemplo n.º 20
0
        private void InternalGetNetworkStream()
        {
            try
            {
                // http://stackoverflow.com/questions/7297173/android-outputstreamwriter-didnt-send-the-data-after-flush-socket
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201512/20151206



                CachedGetStream = (NetworkStream)(object)new __NetworkStream
                {
                    InternalInputStream  = InternalSocket.getInputStream(),
                    InternalOutputStream = InternalSocket.getOutputStream()
                };
            }
            catch
            {
                Console.WriteLine("err InternalGetNetworkStream");
                throw;
            }
        }
Exemplo n.º 21
0
        public void Dispose()
        {
            if (!IsDisposed)
            {
                ServerEndPoint = null;
                InternalSocket.Disconnect(false);
                InternalSocket.Shutdown(SocketShutdown.Both);
                InternalSocket.Dispose();

                foreach (var client in ConnectedClients)
                {
                    RemoveClient(client.Value);
                }

                AllowedAccounts.RemoveRange(0, AllowedAccounts.Count);

                AllowedAccounts  = null;
                ConnectedClients = null;
                IsDisposed       = true;
            }
        }
Exemplo n.º 22
0
        public Task ConnectAsync(string host, int port)
        {
            // X:\jsc.svn\examples\java\android\forms\InteractivePortForwarding\InteractivePortForwarding\UserControl1.cs
            var c = new TaskCompletionSource <object>();

            __Task.Run(
                delegate
            {
                var sw = Stopwatch.StartNew();

                try
                {
                    //Caused by: java.net.SocketTimeoutException: Connection timed out
                    //       at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
                    //       at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:357)
                    //       at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
                    //       at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
                    //       at java.net.Socket.connect(Socket.java:1002)
                    //       at java.net.Socket.connect(Socket.java:945)
                    //       at ScriptCoreLibJava.BCLImplementation.System.Net.Sockets.__TcpClient.Connect(__TcpClient.java:96)

                    InternalSocket.setSoTimeout(150000);

                    InternalSocket.connect(new java.net.InetSocketAddress(host, port));

                    c.SetResult(null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Connect fault " + new { host, port, sw.ElapsedMilliseconds, ex.Message, ex.StackTrace });

                    //throw;
                }
            }
                );

            return(c.Task);
        }
        public async Task read(byte[] abyte0, int j)
        {
            try
            {
                int i = 0;                 // was parameter
                int k;
                for (; j > 0; j -= k)
                {
                    if (PendingBytes < j)
                    {
                        Task receiveAwaitable = InternalSocket.Receive();

                        //TODO: This is a hack to prevent a race condition of the bytes having been received in the middle
                        //of this call. I've gone over it logically and this condition CAN happen and this WILL logically
                        //mitigate it.
                        if (PendingBytes < j)
                        {
                            await receiveAwaitable;
                        }
                    }

                    lock (SyncObj)
                    {
                        if (MessageQueue.Count > 0 || LeftoverArraySegment.HasValue)
                        {
                            ArraySegment <byte> bytes = LeftoverArraySegment.HasValue ? LeftoverArraySegment.Value : MessageQueue.Peek();

                            if (bytes.Count == j || j > bytes.Count)                             //if it's exactly enough
                            {
                                Buffer.BlockCopy(bytes.Array, bytes.Offset, abyte0, i, bytes.Count);
                                AOTCompatibleArrayPool <byte> .SharedSafe.Return(bytes.Array);

                                //Depends on the source
                                if (LeftoverArraySegment.HasValue)
                                {
                                    LeftoverArraySegment = null;
                                }
                                else
                                {
                                    MessageQueue.Dequeue();
                                }

                                //Used all bytes (could be more than we read,
                                k = bytes.Count;
                            }
                            else                            // if (j < bytes.Count)
                            {
                                //We have to do this before, if we DON'T have a pending segment
                                //to process then we dequeue because we've actually peeked this one we're referencing in
                                //the case where we do have one is where it's null.
                                if (!LeftoverArraySegment.HasValue)
                                {
                                    MessageQueue.Dequeue();
                                }

                                //We have TO MANY bytes and so we'll have some left over.
                                Buffer.BlockCopy(bytes.Array, bytes.Offset, abyte0, i, j);
                                LeftoverArraySegment = new ArraySegment <byte>(bytes.Array, bytes.Offset + j, bytes.Count - j);

                                //Used all bytes technically
                                k = j;
                            }

                            PendingBytes -= k;
                        }
                        else
                        {
                            k = 0;
                        }
                    }

                    i += k;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Internal WebSocket Read Multiple Error: {e}");
                throw;
            }
        }
 public async Task write(int i, byte[] abyte0)
 {
     await InternalSocket.Send(abyte0, 0, i);
 }
 public void close()
 {
     InternalSocket.Close();
 }
Exemplo n.º 26
0
 private void SendCallback(IAsyncResult ar)
 {
     InternalSocket.EndSend(ar);
 }
Exemplo n.º 27
0
        private async Task ConnectClientInternal()
        {
            if (_socket != null)
            {
                throw new Exception("connect() is already called");
            }
            try
            {
                int    port = (_uri.Port != -1) ? _uri.Port : (_uri.Scheme.Equals("wss") ? 443 : 80);
                string path = (_uri.AbsolutePath != null) ? _uri.AbsolutePath : "/";
                if (_uri.Query != null)
                {
                    path += "?" + _uri.Query;
                }
                string originScheme = _uri.Scheme.Equals("wss") ? "https" : "http";
                Uri    origin       = new Uri(originScheme + "://" + _uri.Host);
                // To fix: get Origin from extraHeaders if set there.
                this._socket = new InternalSocket();
                await this._socket.ConnectAsync(_uri.Host, port);

                if (_uri.Scheme.Equals("wss"))
                {
                    await this._socket.UpgradeToSslAsync(_uri.Host);
                }
                string     key    = WebSocketHelper.CreateClientKey();
                DataWriter writer = new DataWriter(_socket.OutputStream);
                writer.WriteString("GET " + path + " HTTP/1.1\r\n");
                writer.WriteString("Upgrade: websocket\r\n");
                writer.WriteString("Connection: Upgrade\r\n");
                writer.WriteString("Host: " + _uri.Host + "\r\n");
                writer.WriteString("Origin: " + origin.ToString() + "\r\n");
                writer.WriteString("Sec-WebSocket-Key: " + key + "\r\n");
                writer.WriteString("Sec-WebSocket-Version: 13\r\n");
                if (_extraRequestHeaders != null)
                {
                    foreach (Http.Header header in _extraRequestHeaders)
                    {
                        writer.WriteString(header.ToString() + "\r\n");
                    }
                }
                writer.WriteString("\r\n");
                await writer.StoreAsync(); //异步发送数据

                writer.DetachStream();     //分离
                writer.Dispose();          //结束writer
                DataReader reader = new DataReader(_socket.InputStream);
                reader.ByteOrder = ByteOrder.LittleEndian;
                //// Read HTTP response status line.
                var startLine = await ReadLine(reader);

                if (startLine == null)
                {
                    throw new Exception("Received no reply from server.");
                }
                Http.StatusLine statusLine = new Http.StatusLine(startLine);
                int             statusCode = statusLine.StatusCode;
                if (statusCode != 101)
                {
                    throw new Exception("wrong HTTP response code: " + statusCode);
                }

                // Read HTTP response headers.
                string line;
                while ((line = await ReadLine(reader)) != null && line.Length > 0)
                {
                    Http.Header header = new Http.Header(line);
                    Debug.WriteLine(line);

                    if (header.HeaderName.Equals("Sec-WebSocket-Accept", StringComparison.OrdinalIgnoreCase))
                    {
                        string receivedAccept = header.HeaderValue;
                        string shouldBeAccept = WebSocketHelper.CreateAccept(key);
                        if (!receivedAccept.Equals(shouldBeAccept))
                        {
                            throw new Exception("Wrong Sec-WebSocket-Accept: " + receivedAccept + " should be: " + shouldBeAccept);
                        }
                    }
                    if (_serverResponseHeaders == null)
                    {
                        _serverResponseHeaders = new List <Http.Header>();
                    }
                    _serverResponseHeaders.Add(header);
                }
                if (this.Opened != null)
                {
                    this.Opened(this, EventArgs.Empty);
                }
                //Upgrade: websocket
                //Connection: Upgrade
                //Sec-WebSocket-Accept: 1xY289lHcEMbLpEBgOYRBBL9N9c=
                //Sec-WebSocket-Protocol: chat
                //Content-Type: application/octet-stream
                //Seq-Id: 667035124
                // Read & process frame
                while (true)
                {
                    FrameParser.Frame frame = await FrameParser.ReadFrame(reader);

                    if (frame != null)
                    {
                        await ProcessIncomingFrame(frame);
                    }
                }
            }
            catch (IOException ex)
            {
                if (this.Closed != null)
                {
                    this.Closed(this, new WebSocketClosedEventArgs(0, "EOF"));
                }
            }
            catch (Exception ex)
            {
                if (this.Closed != null)
                {
                    this.Closed(this, new WebSocketClosedEventArgs(0, ex.Message));
                }
            }
            finally
            {
                Disconnect();
            }
        }
Exemplo n.º 28
0
 public void Dispose()
 {
     InternalSocket.Close();
 }