Exemplo n.º 1
0
 public override void Handle(NetStream stream, Command command)
 {
     this.serverObj.ReadValue(command, (index, valuetype, value) => {
         stream.Write(index);//写index
         stream.Write((int)valuetype);
         if (valuetype == PointValueType.Short)
         {
             stream.Write((short)value);
         }
         else if (valuetype == PointValueType.Int)
         {
             stream.Write((int)value);
         }
         else if (valuetype == PointValueType.Float)
         {
             stream.Write((float)value);
         }
         else if (valuetype == PointValueType.String)
         {
             byte[] bs = System.Text.Encoding.UTF8.GetBytes((string)value);
             stream.Write(bs.Length);
             stream.Write(bs);
         }
         else
         {
             stream.Dispose();
         }
     });
 }
Exemplo n.º 2
0
        public void Dispose()
        {
            if (SslStream != null)
            {
                SslStream.Dispose();
                SslStream.Close();
            }
            NetStream.Dispose();
            NetStream.Close();

            Socket.Dispose();
            Socket.Close();
        }
Exemplo n.º 3
0
        public void Disconnected()
        {
            try
            {
                TcpClient.Shutdown(SocketShutdown.Both);
                if (OnDisconnected != null)
                {
                    OnDisconnected.Invoke(this);
                }
            }
            catch { }

            try
            {
                NetStream.Close();
                TcpClient.Close();
                NetStream.Dispose();
                TcpClient.Dispose();
                ClientMS.Dispose();
            }
            catch { }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 关闭TCP连接
        /// </summary>
        /// <returns>假如关闭成功,返回1,否则返回0</returns>
        public int Close()
        {
            LastErrorMessage = string.Empty;
            int result = 1;

            try
            {
                if (BaseClient != null && BaseClient.Connected)
                {
                    ThreadAbort(); //终止重连线程

                    //关闭流并释放资源
                    NetStream.Close();
                    NetStream.Dispose();
                    BaseClient.Close();
                    ServerIp           = null;
                    ServerPort         = 0;
                    IsConnected        = false;
                    IsConnected_Socket = false;
                    //调用连接断开事件委托
                    if (Disconnected != null)
                    {
                        Disconnected.BeginInvoke(Name, new EventArgs(), null, null);
                    }

                    BaseClient = null;
                    raiser.Stop();
                }
            }
            catch (Exception e)
            {
                LastErrorMessage = string.Format("关闭TCP连接{0}失败:{1}", Name, e.Message);
                FileClient.WriteExceptionInfo(e, LastErrorMessage, false);
                result = 0;
                throw; //假如不需要抛出异常,注释此行
            }

            return(result);
        }
        void runForSend()
        {
            var buffer = new List <byte>(20480);

            while (!_disposed || _queue.Count > 0)
            {
                _event.WaitOne();
                _event.Reset();

                while (_queue.TryDequeue(out OpAction <T> item))
                {
                    while (!_disposed)
                    {
                        try
                        {
                            ContentAction action = new ContentAction();
                            action.Type = item.Type;

                            if (item.Data != null)
                            {
                                action.KeyValue = _propertyInfo.GetValue(item.Data).ToString();
                                action.Data     = item.Data.ToJsonString();
                            }
                            var bs    = Encoding.UTF8.GetBytes(action.ToJsonString());
                            var lenbs = BitConverter.GetBytes(bs.Length);
                            buffer.AddRange(lenbs);
                            buffer.AddRange(bs);

                            if (buffer.Count > 10240)
                            {
                                bs = buffer.ToArray();
                                buffer.Clear();
                                _stream.Write(bs);
                            }

                            if (item.CallBack != null)
                            {
                                item.CallBack();
                            }

                            if (item.Type == ActionType.CheckSaved)
                            {
                                if (buffer.Count > 0)
                                {
                                    bs = buffer.ToArray();
                                    buffer.Clear();
                                    _stream.Write(bs);
                                }

                                try
                                {
                                    _stream.ReadBoolean();
                                }
                                catch
                                {
                                }
                                _stream.Dispose();
                                return;
                            }
                            break;
                        }
                        catch
                        {
                            _stream.Dispose();
                            try
                            {
                                init();
                            }
                            catch
                            {
                                _stream = null;
                            }
                        }
                    }
                }
            }

            _stream.Dispose();
        }
Exemplo n.º 6
0
        public static void Run()
        {
            Console.WriteLine("Testing streams");

            string appId = "NetStreamTest";
            int    port  = 20001;

            var serverThread = new Thread(() =>
            {
                var config = new NetPeerConfiguration(appId)
                {
                    AcceptIncomingConnections = true,
                    Port          = port,
                    AutoExpandMTU = true
                };
                var server = new NetServer(config);
                server.Start();

                Task.Run(() =>
                {
                    while (true)
                    {
                        Console.WriteLine("Server Incoming: " +
                                          server.Statistics.IncomingRecycled + " / " +
                                          server.Statistics.IncomingAllocated);

                        Thread.Sleep(500);
                    }
                });

                void OnStream(NetStream stream)
                {
                    int transferred = 0;

                    var t = new Thread(() =>
                    {
                        Span <byte> tmp = stackalloc byte[1024 * 512];
                        int read;
                        while ((read = stream.Read(tmp)) > 0)
                        {
                            //Console.WriteLine("Server Stream Read: " + tmp[0]);
                            transferred += read;
                        }

                        Console.WriteLine($"Server Stream {stream.Channel} Read Finished: {transferred}");
                    });
                    t.Name = "Client Stream";
                    t.Start();

                    Task.Run(() =>
                    {
                        while (t.IsAlive)
                        {
                            Console.WriteLine($"Server Stream {stream.Channel} Read Transferred: " + transferred);
                            Thread.Sleep(1000);
                        }
                    });
                }

                while (server.TryReadMessage(5000, out var message))
                {
                    switch (message.MessageType)
                    {
                    case NetIncomingMessageType.StatusChanged:
                        Console.WriteLine("Server Status: " + message.ReadEnum <NetConnectionStatus>());
                        break;

                    case NetIncomingMessageType.Data:
                        Console.WriteLine("Server Data: " + message.ReadString());
                        break;

                    /*
                     * case NetIncomingMessageType.StreamMessage:
                     * {
                     *  var type = (NetStreamMessageType)message.ReadByte();
                     *  int channel = message.SequenceChannel;
                     *
                     *  if (type != NetStreamMessageType.Data)
                     *      Console.WriteLine("Server Stream: " + type);
                     *
                     *  var connection = message.SenderConnection;
                     *  if (connection == null)
                     *  {
                     *      // send error message back to sender
                     *      break;
                     *  }
                     *
                     *  ref NetStream? stream = ref connection._openStreams[channel];
                     *  switch (type)
                     *  {
                     *      case NetStreamMessageType.Open:
                     *          if (stream != null)
                     *          {
                     *              // send "AlreadyOpen" message
                     *              break;
                     *          }
                     *          stream = new NetStream(server.DefaultScheduler, connection, channel);
                     *
                     *          OnStream(stream);
                     *          break;
                     *
                     *      case NetStreamMessageType.Data:
                     *          if (stream == null)
                     *          {
                     *              // send "NotOpen" message
                     *              break;
                     *          }
                     *          stream.OnDataMessage(message);
                     *          break;
                     *
                     *      case NetStreamMessageType.Close:
                     *          if (stream == null)
                     *          {
                     *              // send "NotOpen" message (or maybe not?)
                     *              break;
                     *          }
                     *          stream.OnCloseMessage(message);
                     *          stream = null;
                     *          break;
                     *  }
                     *  break;
                     * }
                     */

                    default:
                        Console.WriteLine("Server " + message.MessageType);
                        break;
                    }
                }
            });

            Thread[] clientThreads = new Thread[4];

            for (int t = 0; t < clientThreads.Length; t++)
            {
                int tt = t;
                clientThreads[t] = new Thread(() =>
                {
                    var config = new NetPeerConfiguration(appId)
                    {
                        AcceptIncomingConnections = false,
                        AutoExpandMTU             = true
                    };
                    var client = new NetClient(config);
                    client.Start();

                    Task.Run(() =>
                    {
                        while (true)
                        {
                            Console.WriteLine("Client " + tt + " Outgoing: " +
                                              client.Statistics.OutgoingRecycled + " / " +
                                              client.Statistics.OutgoingAllocated);

                            Thread.Sleep(500);
                        }
                    });

                    NetConnection connection = client.Connect(new IPEndPoint(IPAddress.Loopback, port));

                    while (connection.Status != NetConnectionStatus.Connected)
                    {
                        if (connection.Status == NetConnectionStatus.Disconnected)
                        {
                            throw new Exception("Failed to connect.");
                        }
                        Thread.Sleep(1);
                    }

                    var msg = client.CreateMessage("hello");
                    connection.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, 0);

                    for (int j = 0; j < 8; j++)
                    {
                        int channel = j;
                        var t       = new Thread(() =>
                        {
                            try
                            {
                                var stream       = new NetStream(client.DefaultScheduler, connection, channel);
                                Span <byte> span = stackalloc byte[1024 * 64];
                                for (int i = 0; i < 1024 * 1024 * 32; i += span.Length)
                                {
                                    stream.Write(span);
                                    Thread.Sleep(100);
                                }
                                stream.Dispose();
                                Console.WriteLine($"Server Stream {channel} Data Written");
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                            }
                        });
                        t.Name = "Server Stream " + j;
                        t.Start();
                    }

                    while (client.TryReadMessage(5000, out var message))
                    {
                        switch (message.MessageType)
                        {
                        case NetIncomingMessageType.StatusChanged:
                            Console.WriteLine("Client Status: " + message.ReadEnum <NetConnectionStatus>());
                            break;

                        case NetIncomingMessageType.Data:
                            Console.WriteLine("Client Data: " + message.ReadString());
                            break;

                        /*
                         * case NetIncomingMessageType.StreamMessage:
                         * {
                         *  var type = (NetStreamMessageType)message.ReadByte();
                         *  int channel = message.SequenceChannel;
                         *
                         *  Console.WriteLine("Client Stream: " + type);
                         *  break;
                         * }
                         */

                        default:
                            Console.WriteLine("Client " + message.MessageType);
                            break;
                        }

                        client.Recycle(message);
                    }
                });
            }

            serverThread.Start();
            for (int i = 0; i < clientThreads.Length; i++)
            {
                clientThreads[i].Start();
            }

            serverThread.Join();
            for (int i = 0; i < clientThreads.Length; i++)
            {
                clientThreads[i].Join();
            }
        }
Exemplo n.º 7
0
        public void Run(string appId, int port, int streams)
        {
            var config = new NetPeerConfiguration(appId)
            {
                AcceptIncomingConnections = false,
                AutoExpandMTU             = true
            };

            config.DisableMessageType(NetIncomingMessageType.DebugMessage);
            var client = new NetClient(config);

            client.Start();

            var logger = Task.Run(() =>
            {
                while (client.Status != NetPeerStatus.NotRunning)
                {
                    Console.WriteLine("Client Outgoing: " +
                                      client.Statistics.OutgoingRecycled + " / " +
                                      client.Statistics.OutgoingAllocated);

                    Thread.Sleep(500);
                }
            });

            NetConnection connection = client.Connect(new IPEndPoint(IPAddress.Loopback, port));

            while (connection.Status != NetConnectionStatus.Connected)
            {
                if (connection.Status == NetConnectionStatus.Disconnected)
                {
                    throw new Exception("Failed to connect.");
                }
                Thread.Sleep(1);
            }

            var msg = client.CreateMessage("hello");

            connection.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, 0);

            for (int j = 0; j < streams; j++)
            {
                int channel = j;
                var t       = new Thread(() =>
                {
                    try
                    {
                        var stream       = new NetStream(client.DefaultScheduler, connection, channel);
                        Span <byte> span = stackalloc byte[1024 * 64];
                        for (int i = 0; i < 1024 * 1024 * 32; i += span.Length)
                        {
                            stream.Write(span);
                            Thread.Sleep(1);
                        }
                        stream.Dispose();
                        Console.WriteLine($"Server Stream {channel} Data Written");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                });
                t.Name = "Server Stream " + j;
                t.Start();
            }

            while (client.TryReadMessage(5000, out var message))
            {
                switch (message.MessageType)
                {
                case NetIncomingMessageType.StatusChanged:
                    Console.WriteLine("Client Status: " + message.ReadEnum <NetConnectionStatus>());
                    break;

                case NetIncomingMessageType.DebugMessage:
                    Console.WriteLine("Client Debug: " + message.ReadString());
                    break;

                case NetIncomingMessageType.WarningMessage:
                    Console.WriteLine("Client Warning: " + message.ReadString());
                    break;

                case NetIncomingMessageType.Data:
                    Console.WriteLine("Client Data: " + message.ReadString());
                    break;

                case NetIncomingMessageType.ErrorMessage:
                    Console.WriteLine("Client Error: " + message.ReadString());
                    break;

                /*
                 * case NetIncomingMessageType.StreamMessage:
                 * {
                 *  var type = (NetStreamMessageType)message.ReadByte();
                 *  int channel = message.SequenceChannel;
                 *
                 *  Console.WriteLine("Client Stream: " + type);
                 *  break;
                 * }
                 */

                default:
                    Console.WriteLine("Client " + message.MessageType);
                    break;
                }

                client.Recycle(message);
            }

            logger.Wait();
        }
 public virtual void Dispose()
 {
     _stream.Dispose();
 }