Beispiel #1
0
		/**
		 * 分帧逻辑
		 * 
		 **/ 
		public ByteBuf TranslateFrame(ByteBuf src)
		{
			while (src.ReadableBytes() > 0)
			{
				switch (status)
				{
				case 0:
					h = src.ReadByte();
					status = 1;
					break;
				case 1:
					l = src.ReadByte();
					len = (short)(((h << 8)&0x0000ff00) | (l));
					frame = new ByteBuf(len + 2);
					frame.WriteShort(len);
					status = 2;
					break;
				case 2:
				    int min=frame.WritableBytes();
					min=src.ReadableBytes()<min?src.ReadableBytes():min;
					if(min>0)
					{
					frame.WriteBytes(src,min);
					}
					if (frame.WritableBytes() <= 0)
					{
						status = 0;
						return frame;
					}
					break;
				}
			}
			return null;
		}
        /**
         * 分帧逻辑
         *
         **/
        public ByteBuf TranslateFrame(ByteBuf src)
        {
            while (src.ReadableBytes() > 0)
            {
                switch (status)
                {
                case STATUS_HEADER:
                    for (; index < header.Length; index++)
                    {
                        if (!(src.ReadableBytes() > 0))
                        {
                            break;
                        }
                        header[index] = (sbyte)src.ReadByte();
                        if (header[index] >= 0)
                        {
                            int length = 0;
                            length = CodedInputStream.newInstance(header, 0, index + 1).readRawVarint32();
                            if (length < 0)
                            {
                                return(null);
                            }
                            len       = length;
                            headerLen = CodedOutputStream.computeRawVarint32Size(len);
                            Console.WriteLine(":" + len + ":" + headerLen);
                            incompleteframe = new ByteBuf(len + headerLen);
                            CodedOutputStream headerOut = CodedOutputStream.newInstance(incompleteframe, headerLen);
                            headerOut.writeRawVarint32(len);
                            headerOut.flush();
                            status = STATUS_CONTENT;
                            break;
                        }
                    }
                    break;

                case STATUS_CONTENT:
                    int l = Math.Min(src.ReadableBytes(), incompleteframe.WritableBytes());
                    if (l > 0)
                    {
                        incompleteframe.WriteBytes(src, l);
                    }
                    if (incompleteframe.WritableBytes() <= 0)
                    {
                        status = STATUS_HEADER;
                        index  = 0;
                        return(incompleteframe);
                    }
                    break;
                }
            }
            return(null);
        }
		/**
		 * 分帧逻辑
		 * 
		 **/ 
		public ByteBuf TranslateFrame(ByteBuf src)
		{
			while (src.ReadableBytes() > 0)
			{
				switch (status)
				{
				case STATUS_HEADER:
					for (; index < header.Length; index++)
					{
						if (!(src.ReadableBytes() > 0))
						{
							break;
						}
						header[index] = (sbyte)src.ReadByte();
						if (header[index] >= 0)
						{
							int length = 0;
							length = CodedInputStream.newInstance(header, 0, index + 1).readRawVarint32();
							if (length < 0)
							{
							    return null;
							}
							len = length;
						    headerLen = CodedOutputStream.computeRawVarint32Size(len);
							Console.WriteLine (":"+len+":"+headerLen);
							incompleteframe = new ByteBuf(len + headerLen);
							CodedOutputStream headerOut = CodedOutputStream.newInstance(incompleteframe, headerLen);
							headerOut.writeRawVarint32(len);
							headerOut.flush();
							status = STATUS_CONTENT;
							break;
						}
					}
					break;
				case STATUS_CONTENT:
					int l = Math.Min(src.ReadableBytes(), incompleteframe.WritableBytes());
					if (l > 0)
					{
						incompleteframe.WriteBytes(src, l);
					}
					if (incompleteframe.WritableBytes() <= 0)
					{
						status = STATUS_HEADER;
						index = 0;
						return incompleteframe;
					}
					break;
				}
			}
			return null;
		}
Beispiel #4
0
        public static void Main(string[] args)
        {
            KcpClient client = new TestKcp();

            client.NoDelay(1, 10, 2, 1);            //fast
            client.WndSize(64, 64);
            client.Timeout(10 * 1000);
            client.SetMtu(512);
            client.SetMinRto(10);
            client.SetConv(121106);
            //client.Connect("119.29.153.92", 2222);
            client.Connect("127.0.0.1", 2222);
            client.Start();
            Thread.Sleep(2000);
            String s = "hi,heoll world! 你好啊!!";
            //for (int i = 0; i < 2; i++)
            //{
            //    s = s + s;
            //}
            ByteBuf bb = new ByteBuf(System.Text.Encoding.UTF8.GetBytes(s));

            Console.WriteLine(bb.ReadableBytes());
            client.Send(bb);
            Console.Read();
        }
Beispiel #5
0
        /**
         * 分帧逻辑
         *
         **/
        public ByteBuf TranslateFrame(ByteBuf src)
        {
            while (src.ReadableBytes() > 0)
            {
                switch (status)
                {
                case 0:
                    h      = src.ReadByte();
                    status = 1;
                    break;

                case 1:
                    l     = src.ReadByte();
                    len   = (short)(((h << 8) & 0x0000ff00) | (l));
                    frame = new ByteBuf(len + 2);
                    frame.WriteShort(len);
                    status = 2;
                    break;

                case 2:
                    frame.WriteBytes(src);
                    if (frame.WritableBytes() <= 0)
                    {
                        status = 0;
                        return(frame);
                    }
                    break;
                }
            }
            return(null);
        }
Beispiel #6
0
        public override void OnMessage(USocket us, ByteBuf bb)
        {
            bb.ReaderIndex(us.getProtocal().HeaderLen());
            short cmd = bb.ReadShort();

            byte[] bs = bb.GetRaw();
            Statics.SetXor(bs, bb.ReaderIndex());
            MemoryStream stream  = new MemoryStream(bs, bb.ReaderIndex(), bb.ReadableBytes());
            object       obj     = ProtoBuf.Serializer.NonGeneric.Deserialize(MessageQueueHandler.GetProtocolType(cmd), stream);
            FieldInfo    success = obj.GetType().GetField("success");

            if (success != null)
            {
                if ((bool)success.GetValue(obj) == true)
                {
                    MessageQueueHandler.PushQueue(cmd, obj);
                }
                else
                {
                    FieldInfo info = obj.GetType().GetField("info");
                    if (info != null)
                    {
                        Debug.LogWarning("下行出错, cmd=" + cmd + ", type=" + MessageQueueHandler.GetProtocolType(cmd).ToString());
                        MessageQueueHandler.PushError(info.GetValue(obj).ToString());
                    }
                }
            }
        }
Beispiel #7
0
        /**
         * 分帧逻辑
         *
         **/
        public ByteBuf TranslateFrame(ByteBuf src)
        {
            while (src.ReadableBytes() > 0)
            {
                switch (status)
                {
                case 0:
                    h      = src.ReadByte();
                    status = 1;
                    break;

                case 1:
                    hl     = src.ReadByte();
                    status = 2;
                    break;

                case 2:
                    lh     = src.ReadByte();
                    status = 3;
                    break;

                case 3:
                    l     = src.ReadByte();
                    len   = h << 24 | hl << 16 | lh << 8 | l;
                    frame = new ByteBuf(len + 4);
                    frame.WriteInt(len);
                    status = 4;
                    break;

                case 4:
                    int min = frame.WritableBytes();
                    min = src.ReadableBytes() < min?src.ReadableBytes() : min;

                    if (min > 0)
                    {
                        frame.WriteBytes(src, min);
                    }
                    if (frame.WritableBytes() <= 0)
                    {
                        status = 0;
                        return(frame);
                    }
                    break;
                }
            }
            return(null);
        }
Beispiel #8
0
 public override void output(ByteBuf msg, Kcp kcp)
 {
     try {
         this.client.Send(msg.GetRaw(), msg.ReadableBytes());
     } catch (Exception exp) {
         HandleException(exp);
     }
 }
Beispiel #9
0
        /**
         * user/upper level send, returns below zero for error
         *
         * @param buffer
         * @return
         */
        public int Send(ByteBuf buffer)
        {
            if (0 == buffer.ReadableBytes())
            {
                return(-1);
            }
            int count;

            if (buffer.ReadableBytes() < mss)
            {
                count = 1;
            }
            else
            {
                count = (buffer.ReadableBytes() + mss - 1) / mss;
            }
            if (255 < count)
            {
                return(-2);
            }
            if (0 == count)
            {
                count = 1;
            }
            for (int i = 0; i < count; i++)
            {
                int size;
                if (buffer.ReadableBytes() > mss)
                {
                    size = mss;
                }
                else
                {
                    size = buffer.ReadableBytes();
                }
                Segment seg = new Segment(size);
                seg.data.WriteBytes(buffer, size);
                seg.frg = count - i - 1;
                snd_queue.Add(seg);
            }
            return(0);
        }
Beispiel #10
0
        /**
         * user/upper level send, returns below zero for error
         *
         * @param buffer
         * @return
         */
        public int Send(ByteBuf buffer)
        {
            if (buffer.ReadableBytes() == 0)
            {
                return(-1);
            }
            // append to previous segment in streaming mode (if possible)
            if (this.stream && this.snd_queue.Count > 0)
            {
                Segment seg = snd_queue.Last();
                if (seg.data != null && seg.data.ReadableBytes() < mss)
                {
                    int capacity = mss - seg.data.ReadableBytes();
                    int extend   = (buffer.ReadableBytes() < capacity) ? buffer.ReadableBytes() : capacity;
                    seg.data.WriteBytes(buffer, extend);
                    if (buffer.ReadableBytes() == 0)
                    {
                        return(0);
                    }
                }
            }
            int count;

            if (buffer.ReadableBytes() <= mss)
            {
                count = 1;
            }
            else
            {
                count = (buffer.ReadableBytes() + mss - 1) / mss;
            }
            if (count > 255)
            {
                return(-2);
            }
            if (count == 0)
            {
                count = 1;
            }
            //fragment
            for (int i = 0; i < count; i++)
            {
                int     size = buffer.ReadableBytes() > mss ? mss : buffer.ReadableBytes();
                Segment seg  = new Segment(size);
                seg.data.WriteBytes(buffer, size);
                seg.frg = this.stream?0:count - i - 1;
                snd_queue.Add(seg);
            }
            return(0);
        }
Beispiel #11
0
        public override void OnMessage(USocket us, ByteBuf bb)
        {
            Console.WriteLine("收到数据:");
            bb.ReaderIndex(us.getProtocal().HeaderLen());

            int          cmd      = bb.ReadShort();
            MemoryStream stream   = new MemoryStream(bb.GetRaw(), bb.ReaderIndex(), bb.ReadableBytes());
            AuthResponse response = ProtoBuf.Serializer.Deserialize <AuthResponse>(stream);

            Console.WriteLine(response.pid);
            Console.WriteLine(response.info);
            Console.WriteLine(response.success);
        }
Beispiel #12
0
        public override void OnMessage(USocket us,ByteBuf bb)
        {
            Console.WriteLine ("收到数据:");
            bb.ReaderIndex (us.getProtocal().HeaderLen());

            int cmd = bb.ReadShort();
            MemoryStream stream = new MemoryStream(bb.GetRaw(),bb.ReaderIndex(),bb.ReadableBytes());
            AuthResponse response= ProtoBuf.Serializer.Deserialize<AuthResponse>(stream);

            Console.WriteLine (response.pid);
            Console.WriteLine(response.info);
            Console.WriteLine(response.success);
        }
Beispiel #13
0
 /**
  * 发送回调
  */
 private void OnSend(object sender, SocketAsyncEventArgs e)
 {
     if (e.SocketError == SocketError.Success)
     {
         ByteBuf bb = e.UserToken as ByteBuf;
         Interlocked.Increment(ref this.sended);
         Interlocked.Add(ref this.bytesSended, bb.ReadableBytes());
     }
     else//发送失败
     {
         this.Close(false);
     }
 }
Beispiel #14
0
            /**
             * encode a segment into buffer
             *
             * @param buf
             * @param offset
             * @return
             */
            public int Encode(ByteBuf buf)
            {
                int off = buf.WriterIndex();

                buf.WriteIntLE(conv);
                buf.WriteByte(cmd);
                buf.WriteByte((byte)frg);
                buf.WriteShortLE((short)wnd);
                buf.WriteIntLE(ts);
                buf.WriteIntLE(sn);
                buf.WriteIntLE(una);
                buf.WriteIntLE(data == null ? 0 : data.ReadableBytes());
                return(buf.WriterIndex() - off);
            }
Beispiel #15
0
        /**
         * 分帧逻辑
         *
         **/
        public ByteBuf TranslateFrame(ByteBuf src)
        {
            while (src.ReadableBytes() > 0)
            {
                switch (status)
                {
                case 0:    //获取长度高位
                    h      = src.ReadByte();
                    status = 1;
                    break;

                case 1:    //获取长度低位
                    l     = src.ReadByte();
                    len   = (short)(((h << 8) & 0x0000ff00) | (l));
                    frame = new ByteBuf(len + 2);
                    frame.WriteShort(len);    //写入长度先
                    status = 2;
                    break;

                case 2:
                    int min = frame.WritableBytes();    //当前帧可写入的
                    min = src.ReadableBytes() < min?src.ReadableBytes() : min;

                    if (min > 0)
                    {
                        frame.WriteBytes(src, min);
                    }
                    if (frame.WritableBytes() <= 0)
                    {
                        status = 0;    //帧写满了
                        return(frame);
                    }
                    break;
                }
            }
            return(null);
        }
Beispiel #16
0
		public override  void OnMessage(USocket us,ByteBuf bb)
		{
			Console.WriteLine ("收到数据:");
			bb.ReaderIndex (us.getProtocal().HeaderLen());

            int cmd = bb.ReadShort();
            Type t=null;
            MemoryStream stream = new MemoryStream(bb.GetRaw(),bb.ReaderIndex(),bb.ReadableBytes());
            object response=ProtoBuf.Serializer.NonGeneric.Deserialize(t,stream);
            /**
			Console.WriteLine (response.pid);
            Console.WriteLine(response.info);
            Console.WriteLine(response.success);
            */
		}
Beispiel #17
0
        public override void OnMessage(USocket us, ByteBuf bb)
        {
            Console.WriteLine("收到数据:");
            bb.ReaderIndex(us.getProtocal().HeaderLen());

            int          cmd      = bb.ReadShort();
            Type         t        = null;
            MemoryStream stream   = new MemoryStream(bb.GetRaw(), bb.ReaderIndex(), bb.ReadableBytes());
            object       response = ProtoBuf.Serializer.NonGeneric.Deserialize(t, stream);

            /**
             *          Console.WriteLine (response.pid);
             * Console.WriteLine(response.info);
             * Console.WriteLine(response.success);
             */
        }
Beispiel #18
0
 /**
  *发送
  */
 public void Send(Frame frame)
 {
     try
     {
         if (this.status == STATUS_CONNECTED)
         {
             this.sending++;
             ByteBuf bb = frame.GetData();
             SocketAsyncEventArgs arg = new SocketAsyncEventArgs();
             arg.SetBuffer(bb.GetRaw(), bb.ReaderIndex(), bb.ReadableBytes());
             arg.UserToken  = bb;
             arg.Completed += new EventHandler <SocketAsyncEventArgs>(OnSend);
             this.clientSocket.SendAsync(arg);
         }
     }
     catch (Exception ex)
     {
         this.Close(false);
     }
 }
Beispiel #19
0
 /**
  *发送
  */
 public IAsyncResult Send(ByteBuf buf)
 {
     try
     {
         byte[] msg=buf.GetRaw();
         IAsyncResult asyncSend = clientSocket.BeginSend (msg,buf.ReaderIndex(),buf.ReadableBytes(),SocketFlags.None,sended,buf);
         return asyncSend;
     }
     catch
     {
         return null;
     }
 }
Beispiel #20
0
 public override void output(ByteBuf msg, Kcp kcp, Object user)
 {
     this.client.Send(msg.GetRaw(), msg.ReadableBytes());
 }
Beispiel #21
0
        /**
         *
         * when you received a low level packet (eg. UDP packet), call it
         *
         * @param data
         * @return
         */
        public int Input(ByteBuf data)
        {
            int s_una = snd_una;

            if (data == null || data.ReadableBytes() < IKCP_OVERHEAD)
            {
                return(-1);
            }
            int offset = 0;

            while (true)
            {
                int  ts;
                int  sn;
                int  length;
                int  una;
                int  conv_;
                int  wnd;
                byte cmd;
                byte frg;
                if (data.ReadableBytes() < IKCP_OVERHEAD)
                {
                    break;
                }
                conv_   = data.ReadInt();
                offset += 4;
                if (conv != conv_)
                {
                    return(-1);
                }
                cmd     = data.ReadByte();
                offset += 1;
                frg     = data.ReadByte();
                offset += 1;
                wnd     = data.ReadShort();
                offset += 2;
                ts      = data.ReadInt();
                offset += 4;
                sn      = data.ReadInt();
                offset += 4;
                una     = data.ReadInt();
                offset += 4;
                length  = data.ReadInt();
                offset += 4;
                if (data.ReadableBytes() < length)
                {
                    return(-2);
                }
                switch ((int)cmd)
                {
                case IKCP_CMD_PUSH:
                case IKCP_CMD_ACK:
                case IKCP_CMD_WASK:
                case IKCP_CMD_WINS:
                    break;

                default:
                    return(-3);
                }
                rmt_wnd = wnd & 0x0000ffff;
                parse_una(una);
                shrink_buf();
                switch (cmd)
                {
                case IKCP_CMD_ACK:
                    if (_itimediff(current, ts) >= 0)
                    {
                        update_ack(_itimediff(current, ts));
                    }
                    parse_ack(sn);
                    shrink_buf();
                    break;

                case IKCP_CMD_PUSH:
                    if (_itimediff(sn, rcv_nxt + rcv_wnd) < 0)
                    {
                        ack_push(sn, ts);
                        if (_itimediff(sn, rcv_nxt) >= 0)
                        {
                            Segment seg = new Segment(length);
                            seg.conv = conv_;
                            seg.cmd  = cmd;
                            seg.frg  = frg & 0x000000ff;
                            seg.wnd  = wnd;
                            seg.ts   = ts;
                            seg.sn   = sn;
                            seg.una  = una;
                            if (length > 0)
                            {
                                seg.data.WriteBytes(data, length);
                            }
                            parse_data(seg);
                        }
                    }
                    break;

                case IKCP_CMD_WASK:
                    // ready to send back IKCP_CMD_WINS in Ikcp_flush
                    // tell remote my window size
                    probe |= IKCP_ASK_TELL;
                    break;

                // do nothing
                case IKCP_CMD_WINS:
                    break;

                default:
                    return(-3);
                }
                offset += length;
            }
            if (_itimediff(snd_una, s_una) > 0)
            {
                if (cwnd < rmt_wnd)
                {
                    int mss_ = mss;
                    if (cwnd < ssthresh)
                    {
                        cwnd++;
                        incr += mss_;
                    }
                    else
                    {
                        if (incr < mss_)
                        {
                            incr = mss_;
                        }
                        incr += (mss_ * mss_) / incr + (mss_ / 16);
                        if ((cwnd + 1) * mss_ <= incr)
                        {
                            cwnd++;
                        }
                    }
                    if (cwnd > rmt_wnd)
                    {
                        cwnd = rmt_wnd;
                        incr = rmt_wnd * mss_;
                    }
                }
            }
            return(0);
        }
Beispiel #22
0
        /**
         * flush pending data
         */
        private void Flush()
        {
            int cur    = current;
            int change = 0;
            int lost   = 0;

            if (updated == 0)
            {
                return;
            }
            Segment seg = new Segment(0);

            seg.conv = conv;
            seg.cmd  = IKCP_CMD_ACK;
            seg.wnd  = wnd_unused();
            seg.una  = rcv_nxt;
            // flush acknowledges
            int c = acklist.Count / 2;

            for (int i = 0; i < c; i++)
            {
                if (buffer.ReadableBytes() + IKCP_OVERHEAD > mtu)
                {
                    this.output.output(buffer, this, user);
                    buffer = new ByteBuf((mtu + IKCP_OVERHEAD) * 3);
                }
                seg.sn = acklist[i * 2 + 0];
                seg.ts = acklist[i * 2 + 1];
                seg.Encode(buffer);
            }
            acklist.Clear();
            // probe window size (if remote window size equals zero)
            if (rmt_wnd == 0)
            {
                if (probe_wait == 0)
                {
                    probe_wait = IKCP_PROBE_INIT;
                    ts_probe   = current + probe_wait;
                }
                else if (_itimediff(current, ts_probe) >= 0)
                {
                    if (probe_wait < IKCP_PROBE_INIT)
                    {
                        probe_wait = IKCP_PROBE_INIT;
                    }
                    probe_wait += probe_wait / 2;
                    if (probe_wait > IKCP_PROBE_LIMIT)
                    {
                        probe_wait = IKCP_PROBE_LIMIT;
                    }
                    ts_probe = current + probe_wait;
                    probe   |= IKCP_ASK_SEND;
                }
            }
            else
            {
                ts_probe   = 0;
                probe_wait = 0;
            }
            // flush window probing commands
            if ((probe & IKCP_ASK_SEND) != 0)
            {
                seg.cmd = IKCP_CMD_WASK;
                if (buffer.ReadableBytes() + IKCP_OVERHEAD > mtu)
                {
                    this.output.output(buffer, this, user);
                    buffer = new ByteBuf((mtu + IKCP_OVERHEAD) * 3);
                }
                seg.Encode(buffer);
            }
            // flush window probing commands
            if ((probe & IKCP_ASK_TELL) != 0)
            {
                seg.cmd = IKCP_CMD_WINS;
                if (buffer.ReadableBytes() + IKCP_OVERHEAD > mtu)
                {
                    this.output.output(buffer, this, user);
                    buffer = new ByteBuf((mtu + IKCP_OVERHEAD) * 3);
                }
                seg.Encode(buffer);
            }
            probe = 0;
            // calculate window size
            int cwnd_temp = Math.Min(snd_wnd, rmt_wnd);

            if (nocwnd == 0)
            {
                cwnd_temp = Math.Min(cwnd, cwnd_temp);
            }
            // move data from snd_queue to snd_buf
            c = 0;
            for (int i = 0; i < snd_queue.Count; i++)
            {
                Segment item = snd_queue[i];
                if (_itimediff(snd_nxt, snd_una + cwnd_temp) >= 0)
                {
                    break;
                }
                Segment newseg = item;
                newseg.conv     = conv;
                newseg.cmd      = IKCP_CMD_PUSH;
                newseg.wnd      = seg.wnd;
                newseg.ts       = cur;
                newseg.sn       = snd_nxt++;
                newseg.una      = rcv_nxt;
                newseg.resendts = cur;
                newseg.rto      = rx_rto;
                newseg.fastack  = 0;
                newseg.xmit     = 0;
                snd_buf.Add(newseg);
                c++;
            }
            if (c > 0)
            {
                snd_queue.RemoveRange(0, c);
            }
            // calculate resent
            int resent = (fastresend > 0) ? fastresend : int.MaxValue;
            int rtomin = (nodelay == 0) ? (rx_rto >> 3) : 0;

            // flush data segments
            for (int i = 0; i < snd_buf.Count; i++)
            {
                Segment segment  = snd_buf[i];
                bool    needsend = false;
                if (segment.xmit == 0)
                {
                    needsend = true;
                    segment.xmit++;
                    segment.rto      = rx_rto;
                    segment.resendts = cur + segment.rto + rtomin;
                }
                else if (_itimediff(cur, segment.resendts) >= 0)
                {
                    needsend = true;
                    segment.xmit++;
                    xmit++;
                    if (nodelay == 0)
                    {
                        segment.rto += rx_rto;
                    }
                    else
                    {
                        segment.rto += rx_rto / 2;
                    }
                    segment.resendts = cur + segment.rto;
                    lost             = 1;
                }
                else if (segment.fastack >= resent)
                {
                    needsend = true;
                    segment.xmit++;
                    segment.fastack  = 0;
                    segment.resendts = cur + segment.rto;
                    change++;
                }
                if (needsend)
                {
                    segment.ts  = cur;
                    segment.wnd = seg.wnd;
                    segment.una = rcv_nxt;
                    int need = IKCP_OVERHEAD + segment.data.ReadableBytes();
                    if (buffer.ReadableBytes() + need > mtu)
                    {
                        this.output.output(buffer, this, user);
                        buffer = new ByteBuf((mtu + IKCP_OVERHEAD) * 3);
                    }
                    segment.Encode(buffer);
                    if (segment.data.ReadableBytes() > 0)
                    {
                        buffer.WriteBytes(segment.data.Duplicate());
                    }
                    if (segment.xmit >= dead_link)
                    {
                        state = -1;
                    }
                }
            }
            // flash remain segments
            if (buffer.ReadableBytes() > 0)
            {
                this.output.output(buffer, this, user);
                buffer = new ByteBuf((mtu + IKCP_OVERHEAD) * 3);
            }
            // update ssthresh
            if (change != 0)
            {
                int inflight = snd_nxt - snd_una;
                ssthresh = inflight / 2;
                if (ssthresh < IKCP_THRESH_MIN)
                {
                    ssthresh = IKCP_THRESH_MIN;
                }
                cwnd = ssthresh + resent;
                incr = cwnd * mss;
            }
            if (lost != 0)
            {
                ssthresh = cwnd / 2;
                if (ssthresh < IKCP_THRESH_MIN)
                {
                    ssthresh = IKCP_THRESH_MIN;
                }
                cwnd = 1;
                incr = mss;
            }
            if (cwnd < 1)
            {
                cwnd = 1;
                incr = mss;
            }
        }
Beispiel #23
0
        /**
         *
         * when you received a low level packet (eg. UDP packet), call it
         *
         * @param data
         * @return
         */
        public int Input(ByteBuf data)
        {
            int una_temp = snd_una;
            int flag = 0, maxack = 0;

            if (data == null || data.ReadableBytes() < IKCP_OVERHEAD)
            {
                return(-1);
            }
            while (true)
            {
                bool readed = false;
                int  ts;
                int  sn;
                int  len;
                int  una;
                int  conv_;
                int  wnd;
                byte cmd;
                byte frg;
                if (data.ReadableBytes() < IKCP_OVERHEAD)
                {
                    break;
                }
                conv_ = data.ReadIntLE();
                if (this.conv != conv_)
                {
                    return(-1);
                }
                cmd = data.ReadByte();
                frg = data.ReadByte();
                wnd = data.ReadShortLE();
                ts  = data.ReadIntLE();
                sn  = data.ReadIntLE();
                una = data.ReadIntLE();
                len = data.ReadIntLE();
                if (data.ReadableBytes() < len)
                {
                    return(-2);
                }
                switch ((int)cmd)
                {
                case IKCP_CMD_PUSH:
                case IKCP_CMD_ACK:
                case IKCP_CMD_WASK:
                case IKCP_CMD_WINS:
                    break;

                default:
                    return(-3);
                }
                rmt_wnd = wnd & 0x0000ffff;
                Parse_una(una);
                Shrink_buf();
                switch (cmd)
                {
                case IKCP_CMD_ACK:
                    if (_itimediff(current, ts) >= 0)
                    {
                        Update_ack(_itimediff(current, ts));
                    }
                    Parse_ack(sn);
                    Shrink_buf();
                    if (flag == 0)
                    {
                        flag   = 1;
                        maxack = sn;
                    }
                    else if (_itimediff(sn, maxack) > 0)
                    {
                        maxack = sn;
                    }
                    break;

                case IKCP_CMD_PUSH:
                    if (_itimediff(sn, rcv_nxt + rcv_wnd) < 0)
                    {
                        Ack_push(sn, ts);
                        if (_itimediff(sn, rcv_nxt) >= 0)
                        {
                            Segment seg = new Segment(len);
                            seg.conv = conv_;
                            seg.cmd  = cmd;
                            seg.frg  = frg & 0x000000ff;
                            seg.wnd  = wnd;
                            seg.ts   = ts;
                            seg.sn   = sn;
                            seg.una  = una;
                            if (len > 0)
                            {
                                seg.data.WriteBytes(data, len);
                                readed = true;
                            }
                            Parse_data(seg);
                        }
                    }
                    break;

                case IKCP_CMD_WASK:
                    // ready to send back IKCP_CMD_WINS in Ikcp_flush
                    // tell remote my window size
                    probe |= IKCP_ASK_TELL;
                    break;

                case IKCP_CMD_WINS:
                    // do nothing
                    break;

                default:
                    return(-3);
                }
                if (!readed)
                {
                    data.SkipBytes(len);
                }
            }
            if (flag != 0)
            {
                Parse_fastack(maxack);
            }
            if (_itimediff(snd_una, una_temp) > 0)
            {
                if (this.cwnd < this.rmt_wnd)
                {
                    if (this.cwnd < this.ssthresh)
                    {
                        this.cwnd++;
                        this.incr += mss;
                    }
                    else
                    {
                        if (this.incr < mss)
                        {
                            this.incr = mss;
                        }
                        this.incr += (mss * mss) / this.incr + (mss / 16);
                        if ((this.cwnd + 1) * mss <= this.incr)
                        {
                            this.cwnd++;
                        }
                    }
                    if (this.cwnd > this.rmt_wnd)
                    {
                        this.cwnd = this.rmt_wnd;
                        this.incr = this.rmt_wnd * mss;
                    }
                }
            }
            return(0);
        }
Beispiel #24
0
 /**
  *发送
  */
 public IAsyncResult Send(ByteBuf buf)
 {
     try
     {
         byte[]       msg       = buf.GetRaw();
         IAsyncResult asyncSend = clientSocket.BeginSend(msg, buf.ReaderIndex(), buf.ReadableBytes(), SocketFlags.None, sended, buf);
         return(asyncSend);
     }
     catch (Exception e)
     {
         return(null);
     }
 }