Example #1
0
        /// <summary>
        /// 扩展长度
        /// </summary>
        private void Extend()
        {
            var array   = new byte[this.setting.MaxBacklog * this.setting.ReceiveBufferSize];
            var offset  = 0;
            var count   = pools.Count;
            var buffers = new SocketBuffer[setting.MaxBacklog];

            for (var i = 0; i < setting.MaxBacklog; i++)
            {
                var segment = new ArraySegment <byte>(array, offset, this.setting.ReceiveBufferSize);
                var buffer  = new SocketBuffer()
                {
                    Group   = new RangeTuple <int, int>(count, i),
                    Segment = segment,
                };
                buffers[i] = buffer;
                offset    += this.setting.ReceiveBufferSize;
            }

            this.pools.Add(buffers);
            foreach (var buf in buffers)
            {
                this.groups.Enqueue(buf.Group);
            }
        }
Example #2
0
    public NetSocket()
    {
        recvBuffer = new SocketBuffer(6, RecvMsgOver);


        recvBuf = new byte[1024] ;
    }
Example #3
0
        private void SendAnnounceRequest(TrackerGetHttpEntry entry)
        {
            StringBuilder builder   = new StringBuilder(1024);
            string        authority = entry.Address.Authority;
            string        resource  = entry.Address.GetComponents(UriComponents.Path, UriFormat.Unescaped);

            builder.Append("GET /");
            builder.Append(resource);

            builder.AppendHash(entry.Request.Hash);
            builder.AppendPeer(entry.Request.Peer ?? context.Configuration.Peer);

            builder.AppendPort(entry.Request);
            builder.AppendEvent(entry.Request);
            builder.AppendProgress(entry.Request);

            builder.Append("&compact=1&no_peer_id=1");

            builder.AppendLine(" HTTP/1.1");
            builder.Append("Host: ");
            builder.AppendLine(authority);
            builder.AppendLine();

            byte[]       data     = Encoding.ASCII.GetBytes(builder.ToString());
            SocketBuffer outgoing = new SocketBuffer(data);

            entry.Status = TrackerGetHttpStatus.Announcing;
            entry.Socket.Send(outgoing, OnSent(entry));
            entry.Socket.Receive(entry.Buffer, OnReceived(entry));
        }
Example #4
0
        static void AcceptCallback(IAsyncResult ar)
        {
            Socket listener = (Socket)ar.AsyncState;

            Socket     connection = listener.EndAccept(ar);
            IPEndPoint remoteEP   = (IPEndPoint)connection.RemoteEndPoint;

            Console.WriteLine("IP[{0}] Port[{1}] : Accepted!!\n",
                              remoteEP.Address,
                              remoteEP.Port);

            // 수신 대기
            SocketBuffer sb = new SocketBuffer();

            sb.Connection = connection;
            connection.BeginReceive(sb.Buffer,
                                    0,
                                    sb.Buffer.Length,
                                    SocketFlags.None,
                                    new AsyncCallback(ReceiveCallback), sb);

            Console.WriteLine("IP[{0}] Port[{1}] : 수신 대기 중...\n",
                              remoteEP.Address,
                              remoteEP.Port);
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="SntpMessageEventArgs" /> class.
        /// </summary>
        /// <param name="channel">Socket channel request is recived on.</param>
        /// <param name="data">Raw data received from socket.</param>
        public DnsMessageEventArgs(SocketChannel channel, SocketBuffer data)
        {
            if (channel == null) throw new ArgumentNullException("channel");
            this.Channel = channel;

            if (data == null) throw new ArgumentNullException("data");
            this.ChannelBuffer = data;

            try
            {
                // Parse the sntp message
                this.RequestMessage = new DnsMessage(data.Buffer);

                // log that the packet was successfully parsed
                Logger.WriteDebug(this, "PACKET with channel id " +
                    this.Channel.ChannelId.ToString() +
                    " successfully parsed from client endpoint " +
                    this.Channel.RemoteEndpoint.ToString());

                if (this.RequestMessage.TransactionId > 0)
                {
                    Logger.WriteInfo(this, "PACKET with message id " +
                        this.RequestMessage.TransactionId.ToHexString("0x") +
                        " successfully parsed from client endpoint " +
                        this.Channel.RemoteEndpoint.ToString());
                }

                Logger.WriteDebug(this.RequestMessage.ToString());
            }
            catch (Exception ex)
            {
                Logger.WriteError(this, "Error parsing message:" + ex.Message.ToString(), ex);
                return;
            }
        }
Example #6
0
        /// <summary>
        ///     Serialize message and add it to the buffer
        /// </summary>
        /// <param name="args">Socket buffer</param>
        public void Send(SocketBuffer args)
        {
            if (!_headerIsSent)
            {
                if (!_headerCreated)
                {
                    var headerLength = CreateHeader(out _contentLength);
                    _headerStream.Position = _contentStream.Position = 0;
                    _headerCreated         = true;
                    _bytesLeftToSend       = headerLength;
                }

                if (_headerStream.CurrentBlockCapacity == 0)
                {
                    _headerStream.MoveNext();
                }
                var toWrite = Math.Min(NetworkingSettings.BufferSize,
                                       Math.Min(_headerStream.CurrentBlockCapacity, _bytesLeftToSend));
                args.SetBuffer(_headerStream.CurrentBlock, _headerStream.CurrentBlockOffset, toWrite);
                _headerStream.Position += toWrite;
            }
            else
            {
                if (_contentStream.CurrentBlockCapacity == 0)
                {
                    _contentStream.MoveNext();
                }
                var toWrite = Math.Min(NetworkingSettings.BufferSize,
                                       Math.Min(_contentStream.CurrentBlockCapacity, _bytesLeftToSend));
                args.SetBuffer(_contentStream.CurrentBlock, _contentStream.CurrentBlockOffset, toWrite);
                _contentStream.Position += toWrite;
            }
        }
Example #7
0
 public TcpSocketSend(SocketStatus status, int count, TcpSocket socket, SocketBuffer buffer)
 {
     this.status = status;
     this.count  = count;
     this.socket = socket;
     this.buffer = buffer;
 }
Example #8
0
        public async Task <string> Send(IPEndPoint endpoint, string message)
        {
            int progress = 0;

            byte[] output = new byte[message.Length];
            byte[] bytes  = Encoding.ASCII.GetBytes(message);

            using (TcpSocket socket = factory.Tcp())
            {
                socket.Bind();

                TcpSocketConnect connected = await socket.Connect(endpoint);

                TcpSocketSend sent = await socket.Send(bytes);

                while (progress < output.Length)
                {
                    SocketBuffer     buffer   = new SocketBuffer(output, progress);
                    TcpSocketReceive received = await socket.Receive(buffer);

                    if (received.Count == 0)
                    {
                        break;
                    }

                    progress += received.Count;
                }
            }

            return(Encoding.ASCII.GetString(output));
        }
Example #9
0
        static void SendCallback(IAsyncResult ar)
        {
            SocketBuffer sb         = (SocketBuffer)ar.AsyncState;
            Socket       connection = sb.Connection;
            IPEndPoint   remoteEP   = (IPEndPoint)connection.RemoteEndPoint;

            Console.WriteLine("IP[{0}] Port[{1}] : 송신 완료!\n",
                              remoteEP.Address,
                              remoteEP.Port);
        }
Example #10
0
        public void Start()
        {
            buffer = new SocketBuffer(1556);
            socket = factory.Udp();

            context.Queue.Add(() =>
            {
                socket.Bind();
                socket.Receive(buffer, OnReceived);
            });
        }
Example #11
0
        private void SendConnectionRequest(TrackerGetUdpEntry entry)
        {
            SocketBuffer outgoing = new SocketBuffer(16);

            Array.Copy(TrackerGetUdpProtocol.Id, 0, outgoing.Data, 0, 8);
            Array.Copy(TrackerGetUdpProtocol.Connect, 0, outgoing.Data, 8, 4);
            Array.Copy(entry.Transaction, 0, outgoing.Data, 12, 4);

            entry.Status = TrackerGetUdpStatus.Connecting;
            socket.Send(entry.Endpoint, outgoing, OnSent(entry));
        }
Example #12
0
        public WorldSocket(Socket socket) : base(socket)
        {
            _connectType     = ConnectionType.Realm;
            _serverChallenge = new byte[0].GenerateRandomKey(16);
            _worldCrypt      = new WorldCrypt();

            _encryptKey = new byte[16];

            _headerBuffer = new SocketBuffer(HeaderSize);
            _packetBuffer = new SocketBuffer(0);
        }
Example #13
0
        public EchoBenchmarkWorker(Stopwatch watch, SocketFactory factory, IPEndPoint endpoint, byte[] outgoing)
        {
            this.watch    = watch;
            this.endpoint = endpoint;

            this.outgoing = outgoing;
            this.incoming = new byte[outgoing.Length];
            this.session  = Stopwatch.StartNew();

            this.factory = factory;
            this.socket  = factory.Tcp();
        }
Example #14
0
        private Connection(IPayloadEncoder encoder, IPayloadDecoder decoder)
        {
            Identifier = Interlocked.Increment(ref _lastId);
            Guid       = Guid.NewGuid();

            _encoder                 = encoder;
            _decoder                 = decoder;
            _readBuffer              = new SocketBuffer(BufferSize);
            _writeBuffer             = new SocketBuffer(BufferSize);
            _decoder.PacketReceived  = OnPayloadReceived;
            _decoder.RawDataReceived = OnRawDataReceived;
        }
Example #15
0
        /// <summary>
        /// 把响应数据写入到SocketAsyncEventArgs中
        /// 写入成功返回true,否则返回false,表示没有数据返回到客户端
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public bool Write(SocketAsyncEventArgs e)
        {
            int          token  = ((AsyncUserToken)e.UserToken).Token;
            SocketBuffer buffer = SocketBuffers.GetOrAdd(token, t =>
            {
                return(new SocketBuffer(Config.MsgHandle, new ClientOption {
                    EndPoint = (IPEndPoint)e.AcceptSocket.RemoteEndPoint
                }));
            });

            return(buffer.Write(e));
        }
Example #16
0
	private void OnReceiveData(SocketBuffer buffer, int offset, int length)
	{
		var currLen = length;
		var currOffset = offset;
		while (packetReader.IsDataEngoughToRead(currLen))
		{
			int readCount = packetReader.Read(buffer, currOffset, currLen);
			buffer.SetBytesUsed(readCount);

			currLen -= readCount;
			currOffset += readCount;
		}
	}
Example #17
0
        //Sample Send Method. You do need a index and to send
        //data to the correct connected client(int index).
        //If you do want send a packet over the network from the server
        //you always have to design a sending method like the sample one.
        //Optinal: (string chatMsg to assign a written text to send over network)
        public static void SendWelcomeMsg(int index)
        {
            //create a new buffer to write data in it!
            SocketBuffer buffer = new SocketBuffer();

            //Assign the identifier to the packet! Never forget this
            //else the client does not now what to do with the received packet.
            buffer.WriteInteger((int)ServerPackets.SChatMsg);
            //add your chatMsg to the packet, so the client can read it out.
            buffer.WriteString("Welcome to the server. You are now conencted with me!");
            //send data over the network. to a specific client. convert the buffer to a byte[] to make it available to send over the network.
            Network.SendDataTo(index, buffer.ToArray());
        }
Example #18
0
        //Sample Send Method. send data to the connected server.
        //If you do want send a packet over the network from the client
        //you always have to design a sending method like the sample one.
        //Optinal: (string chatMsg to assign a written text to send over network)
        public static void SendThankYou()
        {
            //create a new buffer to write data in it!
            SocketBuffer buffer = new SocketBuffer();

            //Assign the identifier to the packet! Never forget this
            //else the server does not now what to do with the received packet.
            buffer.WriteInteger((int)ClientPackets.CChatMsg);
            //add your chatMsg to the packet, so the client can read it out.
            buffer.WriteString("Thank you im glad that I'm able to connect to the server!");
            //send data over the network to the connected server. convert the buffer to a byte[] to make it available to send over the network.
            Network.SendData(buffer.ToArray());
        }
        /// <summary>
        ///     We've received bytes from the socket. Build a message out of them.
        /// </summary>
        /// <param name="buffer">Buffer</param>
        public void ProcessReadBytes(SocketChannel channel, SocketBuffer buffer)
        {
            _channel = channel;

            var receiveBufferOffset      = buffer.Offset;
            var bytesLeftInReceiveBuffer = buffer.BytesTransferred;

            while (true)
            {
                if (bytesLeftInReceiveBuffer <= 0)
                {
                    break;
                }

                if (!_isHeaderParsed)
                {
                    var offsetBefore = receiveBufferOffset;
                    receiveBufferOffset = _headerParser.Parse(buffer, receiveBufferOffset);
                    if (!_isHeaderParsed)
                    {
                        return;
                    }

                    bytesLeftInReceiveBuffer -= receiveBufferOffset - offsetBefore;
                    _frameContentBytesLeft    = _message.ContentLength;
                    if (_frameContentBytesLeft == 0)
                    {
                        TriggerMessageReceived(_message);
                        _message        = null;
                        _isHeaderParsed = false;
                        continue;
                    }

                    _message.Body = new MemoryStream();
                }

                var bytesRead    = BytesProcessed(buffer.Offset, receiveBufferOffset);
                var bytesToWrite = System.Math.Min(_frameContentBytesLeft, buffer.BytesTransferred - bytesRead);
                _message.Body.Write(buffer.Buffer, receiveBufferOffset, bytesToWrite);
                _frameContentBytesLeft   -= bytesToWrite;
                receiveBufferOffset      += bytesToWrite;
                bytesLeftInReceiveBuffer -= bytesToWrite;
                if (_frameContentBytesLeft == 0)
                {
                    _message.Body.Position = 0;
                    TriggerMessageReceived(_message);
                    Clear();
                }
            }
        }
Example #20
0
        private void OnSent(TcpSocketSend data)
        {
            if (data.Status == SocketStatus.OK)
            {
                outgoing = new SocketBuffer(data.Buffer.Data, data.Buffer.Offset + data.Count, data.Buffer.Count - data.Count);

                if (incoming.Count > 0)
                {
                    socket.Receive(incoming, OnReceived);
                }
                else if (outgoing.Count > 0)
                {
                    socket.Send(outgoing, OnSent);
                }
                else
                {
                    incoming = new SocketBuffer(incoming.Data);
                    outgoing = new SocketBuffer(outgoing.Data);

                    if (session.Elapsed > TimeSpan.FromMinutes(1))
                    {
                        socket  = factory.Tcp();
                        session = Stopwatch.StartNew();

                        socket.Bind();
                        socket.Connect(endpoint, OnConnected);
                        data.Socket.Dispose();
                    }
                    else
                    {
                        socket.Send(outgoing, OnSent);
                    }
                }
            }
            else
            {
                Console.WriteLine("OnSent");
                socket.Dispose();
            }

            counter += data.Count;

            if (counter - previous > 1024 * 1024 * 1024)
            {
                previous = counter;

                Console.WriteLine($"{counter}: {counter / watch.ElapsedMilliseconds}");
            }
        }
Example #21
0
        private void OnReceived(TcpSocketReceive received)
        {
            if (received.Count > 0 && received.Status == SocketStatus.OK)
            {
                int          count  = received.Count;
                SocketBuffer buffer = new SocketBuffer(data, 0, count);

                received.Socket.Send(buffer, OnSent);
            }
            else
            {
                factory.Release(this);
                received.Socket.Dispose();
            }
        }
Example #22
0
        private int Read(SocketBuffer buffer, ref int offset)
        {
            if (_lookAhead != -1)
            {
                var tmp = _lookAhead;
                _lookAhead = -1;
                return(tmp);
            }

            if (offset - buffer.BaseOffset >= buffer.BytesTransferred)
            {
                return(-1);
            }

            return(buffer.Buffer[offset++]);
        }
Example #23
0
        public void Send(NetworkOutgoingMessage message, Action callback)
        {
            if (listener.IsAvailable(identifier))
            {
                DataBlock    block  = new NetworkOutgoingBlock(memory.Data, offset, message.Length);
                SocketBuffer buffer = new SocketBuffer(memory.Data, offset, message.Length);

                message.ToBytes(block);
                encryptor?.Encrypt(memory.Data, offset, message.Length);

                offset += message.Length;
                parts.Add(offset);

                socket.Send(buffer, OnSent(callback));
            }
        }
Example #24
0
        //Handles the ChatMsg Packet you have assigned at "InitPackets"
        private static void HandleChatMsg(int index, byte[] data)
        {
            //Creates a new instance of the buffer to read out the packet.
            SocketBuffer buffer = new SocketBuffer();

            //writes the packet into a list to make it avaiable to read it out.
            buffer.WriteBytes(data);
            //INFO: You always have to read out the data as you did send it.
            //In this case you always have to first to read out the packet identifier.
            int packetIdentify = buffer.ReadInteger();
            //In the server side you now send a string as next so you have to read out the string as next.
            string msg = buffer.ReadString();

            //print out the string msg you did send from the server.
            Console.WriteLine("Got Packet Nr '{0}' with message: '{1}' from connection Nr: '{2}'", packetIdentify, msg, index);
        }
Example #25
0
        /// <summary>
        ///     Will try to parse everything in the buffer
        /// </summary>
        /// <param name="buffer">Buffer to read from.</param>
        /// <param name="offset">Where to start parsing in the buffer.</param>
        /// <returns>offset where the parser ended.</returns>
        /// <remarks>
        ///     <para>
        ///         Do note that the parser is for the header only. The <see cref="Completed" /> event will
        ///         indicate that there might be body bytes left in the buffer. You have to handle them by yourself.
        ///     </para>
        /// </remarks>
        public int Parse(SocketBuffer buffer, int offset)
        {
            int theByte;

            while ((theByte = Read(buffer, ref offset)) != -1)
            {
                var ch = (char)theByte;
                _parserMethod(ch);
                if (_isCompleted)
                {
                    break;
                }
            }

            _isCompleted = false;
            return(offset);
        }
Example #26
0
        //Handles the ChatMsg Packet you have assigned at "InitPackets"
        private static void HandleChatMsg(byte[] data)
        {
            //Creates a new instance of the buffer to read out the packet.
            SocketBuffer buffer = new SocketBuffer();

            //writes the packet into a list to make it avaiable to read it out.
            buffer.WriteBytes(data);
            //INFO: You always have to read out the data as you did send it.
            //In this case you always have to first to read out the packet identifier.
            int packetIdentify = buffer.ReadInteger();
            //In the server side you now send a string as next so you have to read out the string as next.
            string msg = buffer.ReadString();

            //print out the string msg you did send from the server.
            Console.WriteLine("Got Packet Nr '{0}' with message: '{1}'", packetIdentify, msg);
            //we have received a welcome message now send a packet back to server to say thank you!
            SocketSend.SendThankYou();
        }
Example #27
0
	public void TestAddData2()
	{
		var buffer = new SocketBuffer(2048);
		var raw = buffer.RawBuffer;

		Assert.AreEqual(2048, buffer.BufferSize);
		Assert.AreEqual(0, buffer.ProducePosition);
		Assert.AreEqual(0, buffer.ConsumePosition);

		var data = System.Text.Encoding.ASCII.GetBytes("hello~");
		var result = buffer.AddData(data);

		Assert.AreEqual(6, buffer.ProducePosition);
		Assert.AreEqual(0, buffer.ConsumePosition);
		Assert.AreEqual(6, buffer.AvailableDataLength);
		Assert.AreEqual(2042, buffer.AvailableSpace);
		Assert.IsTrue(result);

		buffer.SetBytesUsed(6);

		data = System.Text.Encoding.ASCII.GetBytes("test");
		buffer.AddData(data);

		var desti = new byte[buffer.CurrentPickingDataLength];
		Array.Copy(raw, buffer.ConsumePosition, desti, 0, buffer.CurrentPickingDataLength);

		var text = System.Text.Encoding.ASCII.GetString(desti);
		Assert.AreEqual(text, "test");

		buffer.SetBytesUsed(4);

		data = System.Text.Encoding.ASCII.GetBytes("test");
		buffer.AddData(data);

		Array.Copy(raw, buffer.ConsumePosition, desti, 0, buffer.CurrentPickingDataLength);

		text = System.Text.Encoding.ASCII.GetString(desti);
		Assert.AreEqual(text, "test");

		buffer.SetBytesUsed(4);


	}
Example #28
0
        private void SendAnnounceRequest(TrackerGetUdpEntry entry)
        {
            SocketBuffer outgoing = new SocketBuffer(98);
            PeerHash     peer     = context.Configuration.Peer;

            outgoing[67] = 0x01;
            outgoing[83] = 0x02;
            outgoing[95] = 0xff;
            outgoing[96] = 0x1f;
            outgoing[97] = 0x90;

            Array.Copy(entry.Connection, 0, outgoing.Data, 0, 8);
            Array.Copy(TrackerGetUdpProtocol.Announce, 0, outgoing.Data, 8, 4);
            Array.Copy(entry.Transaction, 0, outgoing.Data, 12, 4);
            Array.Copy(entry.Request.Hash.ToBytes(), 0, outgoing.Data, 16, 20);
            Array.Copy(peer.ToBytes(), 0, outgoing.Data, 36, 20);

            entry.Status = TrackerGetUdpStatus.Announcing;
            socket.Send(entry.Endpoint, outgoing, OnSent(entry));
        }
Example #29
0
        /// <summary>
        ///  Remote client connects and makes a request.
        /// </summary>
        private void OnClientConnect(object sender, ClientConnectedEventArgs args)
        {
            SocketBuffer channelBuffer = args.ChannelBuffer;

            if (channelBuffer != null &&
                args.Channel.IsConnected &&
                channelBuffer.BytesTransferred >= Constants.DNS_MIN_MESSAGE_SIZE &&
                channelBuffer.BytesTransferred <= Constants.DNS_MAX_MESSAGE_SIZE)
            {
                Logger.WriteDebug(this, "PACKET request with channel id " +
                                  args.Channel.ChannelId.ToString() +
                                  " was received from " +
                                  args.Channel.RemoteEndpoint.ToString() +
                                  " and queued for processing...");

                DnsMessageEventArgs messageArgs = new DnsMessageEventArgs(args.Channel, args.ChannelBuffer);
                OnDnsMessageReceived(this, messageArgs);

                ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessRequest), messageArgs);
            }
        }
Example #30
0
        public static void HandleSocketData(int index, byte[] data)
        {
            //creating a new instance of 'SocketBuffer' to read out the packet.
            SocketBuffer buffer = new SocketBuffer();

            //writing incoming packet to the buffer.
            buffer.WriteBytes(data);
            //reads out the packet to see which packet we got.
            int packet = buffer.ReadInteger();

            //closes the buffer.
            buffer.Dispose();
            //checking if we are listening to that packet in the _packets Dictionary.
            if (_packets.TryGetValue(packet, out Packets _packet))
            {
                //checks which Method is assigned to the packet and executes it,
                //index: the socket which sends the data
                //data: the packet byte [] with the information.
                _packet.Invoke(index, data);
            }
        }
Example #31
0
        static void ReceiveCallback(IAsyncResult ar)
        {
            SocketBuffer sb         = (SocketBuffer)ar.AsyncState;
            Socket       connection = sb.Connection;
            IPEndPoint   remoteEP   = (IPEndPoint)connection.RemoteEndPoint;

            try
            {
                int    receiveSize   = connection.EndReceive(ar);
                string receiveString = Encoding.UTF8.GetString(sb.Buffer, 0, receiveSize);
                Console.WriteLine("IP[{0}] Port[{1}] : 수신 완료!",
                                  remoteEP.Address,
                                  remoteEP.Port);
                Console.WriteLine("수신 데이터: {0}\n", receiveString);

                // 송신
                string sendString =
                    string.Format("당신은 {0}입니다. \n수신 데이터는 {1}였습니다.",
                                  remoteEP.Address, receiveString);
                Console.WriteLine("IP[{0}] Port[{1}] : 「{2}」를 송신 중\n",
                                  remoteEP.Address,
                                  remoteEP.Port,
                                  sendString);

                byte[] sendData = Encoding.UTF8.GetBytes(sendString);
                connection.BeginSend(sendData,
                                     0,
                                     sendData.Length,
                                     SocketFlags.None,
                                     new AsyncCallback(SendCallback),
                                     sb);
            }
            catch (SocketException)
            {
                // 수신 대기 중 클라이언트에서 접속을 끊은 경우 Exception이 발생한다.
                Console.WriteLine("IP[{0}] Port[{1}] : 리모트에서 접속이 끊어졌습니다.\n",
                                  remoteEP.Address,
                                  remoteEP.Port);
            }
        }
Example #32
0
        public void CanTransferDataUsingUdpSockets()
        {
            using (CompletionThread worker = new CompletionThread())
            {
                worker.Start();

                using (ManualResetEvent sync = new ManualResetEvent(false))
                {
                    IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 44556);
                    byte[]     data     = Encoding.ASCII.GetBytes("abc");

                    SocketBuffer  buffer  = new SocketBuffer(data);
                    SocketFactory factory = new SocketFactory(worker);

                    using (UdpSocket sender = factory.Udp())
                        using (UdpSocket receiver = factory.Udp())
                        {
                            sender.Bind();
                            receiver.Bind(endpoint.Port);

                            receiver.Receive(new SocketBuffer(10), received =>
                            {
                                Assert.That(received.Status, Is.EqualTo(SocketStatus.OK));
                                Assert.That(received.Count, Is.EqualTo(3));
                                Assert.That(received.Buffer.Data.Take(3), Is.EqualTo(data));

                                sync.Set();
                            });

                            sender.Send(endpoint, buffer, sent =>
                            {
                                Assert.That(sent.Status, Is.EqualTo(SocketStatus.OK));
                                Assert.That(sent.Count, Is.EqualTo(3));
                            });
                        }

                    Assert.That(sync.WaitOne(200), Is.True);
                }
            }
        }
        /// <summary>
        /// </summary>
        /// <param name="readBuffer"></param>
        /// <param name="encoder"></param>
        /// <param name="decoder"></param>
        /// <param name="sslStreamBuilder">Used to wrap the socket with a SSL stream</param>
        public SecureTcpChannel(IBufferSlice readBuffer, IMessageEncoder encoder, IMessageDecoder decoder, ISslStreamBuilder sslStreamBuilder) {
            if (readBuffer == null) throw new ArgumentNullException("readBuffer");
            if (encoder == null) throw new ArgumentNullException("encoder");
            if (decoder == null) throw new ArgumentNullException("decoder");
            if (sslStreamBuilder == null) throw new ArgumentNullException("sslStreamBuilder");

            _encoder = encoder;
            _decoder = decoder;
            _sslStreamBuilder = sslStreamBuilder;
            _decoder.MessageReceived = OnMessageReceived;

            _sendCompleteAction = (channel, message) => { };
            _disconnectAction = (channel, exception) => { };
            ChannelFailure = (channel, error) => HandleDisconnect(SocketError.ProtocolNotSupported);

            RemoteEndpoint = EmptyEndpoint.Instance;

            _readBuffer = new SocketBuffer(readBuffer);
            _writeBuffer = new SocketBuffer();
            ChannelId = GuidFactory.Create().ToString();
            Data = new ChannelData();
        }
Example #34
0
		public NetworkInterface()
		{
			sendBuffer = new SocketBuffer(20480);
			receiveBuffer = new SocketBuffer(20480);
		}
Example #35
0
	public void TestAddData()
	{
		var buffer = new SocketBuffer(10);

		Assert.AreEqual(10, buffer.BufferSize);
		Assert.AreEqual(0, buffer.ProducePosition);
		Assert.AreEqual(0, buffer.ConsumePosition);

		var data = System.Text.Encoding.ASCII.GetBytes("hello!");
		var result = buffer.AddData(data);

		Assert.AreEqual(6, buffer.ProducePosition);
		Assert.AreEqual(0, buffer.ConsumePosition);
		Assert.AreEqual(6, buffer.AvailableDataLength);
		Assert.AreEqual(4, buffer.AvailableSpace);
		Assert.IsTrue(result);

		//cannot add
		data = System.Text.Encoding.ASCII.GetBytes("world");

		result = buffer.AddData(data);
		Assert.IsTrue(!result);

		buffer.SetBytesUsed(4);

		data = System.Text.Encoding.ASCII.GetBytes("world123");
		result = buffer.AddData(data);

		Assert.IsTrue(result);
		Assert.AreEqual(4, buffer.ProducePosition);
		Assert.AreEqual(4, buffer.ConsumePosition);
		Assert.AreEqual(10, buffer.AvailableDataLength);
		Assert.AreEqual(0, buffer.AvailableSpace);

		var raw = buffer.RawBuffer;
		var echo = System.Text.Encoding.ASCII.GetString(raw);
		Debug.Log("echo:" + echo);

		buffer.SetBytesUsed(6);

		data = System.Text.Encoding.ASCII.GetBytes("456789");
		buffer.AddData(data);
		Assert.IsTrue(result);

		Assert.AreEqual(0, buffer.ProducePosition);
		Assert.AreEqual(0, buffer.ConsumePosition);
		Assert.AreEqual(10, buffer.AvailableDataLength);
		Assert.AreEqual(0, buffer.AvailableSpace);

		echo = System.Text.Encoding.ASCII.GetString(raw);
		Debug.Log("echo:" + echo);

		buffer.SetBytesUsed(6);

		data = System.Text.Encoding.ASCII.GetBytes("abc");
		buffer.AddData(data);

		Assert.AreEqual(3, buffer.ProducePosition);
		Assert.AreEqual(6, buffer.ConsumePosition);
		Assert.AreEqual(7, buffer.AvailableDataLength);
		Assert.AreEqual(3, buffer.AvailableSpace);

		echo = System.Text.Encoding.ASCII.GetString(raw);
		Debug.Log("echo:" + echo);


	}
Example #36
0
 /// <summary>
 /// Initial set
 /// </summary>
 /// <param name="CurrentReceiveBuffer">The current received buffer of socket</param>
 public DataReceivedEventArgs(SocketBuffer CurrentReceiveBuffer)
 {
     buffer_CurrentReceiveBuffer = CurrentReceiveBuffer;
 }
Example #37
0
 /// <summary>
 /// The timer function of receiving data
 /// </summary>
 protected void TimerReceive_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     timer_TimerReceive.Stop();
     try
     {
         if (!bool_IsOnReceivingData)
         {
             bool_IsOnReceivingData = true;
             if (ReceiveBuffer.AvailableLength > 0) //接收缓冲内有内容
             {
                 SocketBuffer BackBuffer = ReceiveBuffer;
                 this.buffer_ReceiveBuffer = new SocketBuffer(BackBuffer.Size);
                 BackBuffer.Dispose();
                 BackBuffer = null;
             }
             socket_Base.BeginReceive(ReceiveBuffer.Bytes, 0, ReceiveBuffer.Size,
                 enum_ReceiveFlags,
                 new AsyncCallback(AsyncReceiveEnd), socket_Base);
         }
     }
     catch
     {
         //判断类型, 视之为断开, 并引发Closed事件
         //在Closed中已经进行了Socket重置
         ChangeSocketState(SocketState.Closed, SocketError.RemoteClose, SocketStateRaiseEventType.IfChanged);
     }
 }
Example #38
0
        /// <summary>
        /// The call back function of async receive
        /// </summary>
        /// <param name="AsyncResult">The async result</param>
        protected void AsyncReceiveEnd(IAsyncResult AsyncResult)
        {
            int ByteReceived = 0;
            try
            {
                ByteReceived = socket_Base.EndReceive(AsyncResult);
            }
            catch (ArgumentException)
            { //此错误出现在当上一个链接已经关闭, 建立了新的socket, 而新一轮的Receive已经开始
                ByteReceived = -1;
            }
            catch
            {
                ByteReceived = 0;
            }

            if (ByteReceived > 0)
            {
                if (State == SocketState.Connected) //判断状态
                {
                    byte[] ReceivedByte = this.buffer_ReceiveBuffer.Bytes; //获取获得的字节
                    this.buffer_ReceiveBuffer.Dispose();                                //释放上次的缓冲区
                    this.buffer_ReceiveBuffer = null;
                    this.buffer_ReceiveBuffer = new SocketBuffer(ReceivedByte, ByteReceived); //建立新缓冲区, 传入字节
                    OnDataReceived(new DataReceivedEventArgs(this.buffer_ReceiveBuffer));
                }
                bool_IsOnReceivingData = false; //控制变量=False, 允许主进程继续使用BeginReceivingData
                if (this.State == SocketState.Connected)
                {
                    timer_TimerReceive.Start();  //再次启动
                }
            }
            else if (ByteReceived == -1)
            {//忽略这种错误, 保持链接
                bool_IsOnReceivingData = false;
            }
            else
            {
                bool_IsOnReceivingData = false;  //控制变量=False, 允许主进程继续使用BeginReceivingData
                //如果没接收到数据, 认为是端口关闭
                ChangeSocketState(SocketState.Closed, SocketError.RemoteClose, SocketStateRaiseEventType.IfChanged);
            }
        }
Example #39
0
 /// <summary>
 /// Dispose method
 /// </summary>
 public void Dispose()
 {
     Close();
     if (socket_Base != null)
     {
         socket_Base = null;
     }
     if (buffer_ReceiveBuffer != null)
     {
         buffer_ReceiveBuffer.Dispose();
         buffer_ReceiveBuffer = null;
     }
 }