Exemplo n.º 1
0
        static void Main(string[] args)
        {
            try
            {
                Client.ConnectWindow connectWindow = new Client.ConnectWindow();
                var dialogResult = connectWindow.ShowDialog();
                if (dialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    TcpServer tcpServer = new TcpServer(new TcpListener(IPAddress.Parse(connectWindow.Adress.Text), int.Parse(connectWindow.PortBox.Text)));

                    Console.WriteLine("Server start");
                    //Action<ReceivedParseInterface> b = tcpServer.Listening;
                    //tcpServer.Listening(new ReceivedParseTest(tcpServer));
                    tcpServer.Listening(new MathOperationMessageParse(tcpServer));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine("END");
            Console.ReadKey();
        }
Exemplo n.º 2
0
 public ReceivedParseTest(TcpServer server)
 {
     serverOperate = server;
 }
Exemplo n.º 3
0
 private void FileReceiverThread()
 {
     FRProvider = new FileReceiver();
     FRServidor = new TcpServer(FRProvider, 7004);
     FRServidor.Start();
 }
Exemplo n.º 4
0
 private void FileServerThread()
 {
     FSProvider = new FileServer();
     FSServidor = new TcpServer(FSProvider, 7005);
     FSServidor.Start();
 }
Exemplo n.º 5
0
        private static IServer StartProtocol(Configuration c, ChatProtocolConfiguration pc, ServerContext ServerContext, TaskFactory Factory, TaskFactory PurifierFactory)
        {
            if (pc.OnTcp)
            {
                var s = pc.Tcp;

                if (!(s.SerializationProtocolType == SerializationProtocolType.Binary || s.SerializationProtocolType == SerializationProtocolType.Json))
                {
                    throw new InvalidOperationException("未知协议类型: " + s.SerializationProtocolType.ToString());
                }

                Func <ISessionContext, IBinaryTransformer, KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer> > VirtualTransportServerFactory;
                if (s.SerializationProtocolType == SerializationProtocolType.Binary)
                {
                    VirtualTransportServerFactory = (Context, t) =>
                    {
                        var p    = ServerContext.CreateServerImplementationWithBinaryAdapter(Factory, Context);
                        var si   = p.Key;
                        var a    = p.Value;
                        var bcps = new BinaryCountPacketServer(a, CommandName => true, t);
                        return(new KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer>(si, bcps));
                    };
                }
                else if (s.SerializationProtocolType == SerializationProtocolType.Json)
                {
                    VirtualTransportServerFactory = (Context, t) =>
                    {
                        var p    = ServerContext.CreateServerImplementationWithJsonAdapter(Factory, Context);
                        var si   = p.Key;
                        var a    = p.Value;
                        var bcps = new JsonLinePacketServer(a, CommandName => true, t);
                        return(new KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer>(si, bcps));
                    };
                }
                else
                {
                    throw new InvalidOperationException();
                }

                var Server  = new TcpServer(ServerContext, VirtualTransportServerFactory, a => Factory.StartNew(a), a => PurifierFactory.StartNew(a));
                var Success = false;

                try
                {
                    Server.Bindings           = s.Bindings.Select(b => new IPEndPoint(IPAddress.Parse(b.IpAddress), b.Port)).ToArray();
                    Server.SessionIdleTimeout = s.SessionIdleTimeout;
                    Server.UnauthenticatedSessionIdleTimeout = s.UnauthenticatedSessionIdleTimeout;
                    Server.MaxConnections          = s.MaxConnections;
                    Server.MaxConnectionsPerIP     = s.MaxConnectionsPerIP;
                    Server.MaxUnauthenticatedPerIP = s.MaxUnauthenticatedPerIP;
                    Server.MaxBadCommands          = s.MaxBadCommands;

                    Server.Start();

                    Console.WriteLine(@"TCP/{0}服务器已启动。结点: {1}".Formats(s.SerializationProtocolType.ToString(), String.Join(", ", Server.Bindings.Select(b => b.ToString() + "(TCP)"))));

                    Success = true;
                }
                finally
                {
                    if (!Success)
                    {
                        Server.Dispose();
                    }
                }

                return(Server);
            }
            else if (pc.OnUdp)
            {
                var s = pc.Udp;

                if (!(s.SerializationProtocolType == SerializationProtocolType.Binary || s.SerializationProtocolType == SerializationProtocolType.Json))
                {
                    throw new InvalidOperationException("未知协议类型: " + s.SerializationProtocolType.ToString());
                }

                Func <ISessionContext, IBinaryTransformer, KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer> > VirtualTransportServerFactory;
                if (s.SerializationProtocolType == SerializationProtocolType.Binary)
                {
                    VirtualTransportServerFactory = (Context, t) =>
                    {
                        var p    = ServerContext.CreateServerImplementationWithBinaryAdapter(Factory, Context);
                        var si   = p.Key;
                        var a    = p.Value;
                        var bcps = new BinaryCountPacketServer(a, CommandName => true, t);
                        return(new KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer>(si, bcps));
                    };
                }
                else if (s.SerializationProtocolType == SerializationProtocolType.Json)
                {
                    VirtualTransportServerFactory = (Context, t) =>
                    {
                        var p    = ServerContext.CreateServerImplementationWithJsonAdapter(Factory, Context);
                        var si   = p.Key;
                        var a    = p.Value;
                        var bcps = new JsonLinePacketServer(a, CommandName => true, t);
                        return(new KeyValuePair <IServerImplementation, IStreamedVirtualTransportServer>(si, bcps));
                    };
                }
                else
                {
                    throw new InvalidOperationException();
                }

                var Server  = new UdpServer(ServerContext, VirtualTransportServerFactory, a => Factory.StartNew(a), a => PurifierFactory.StartNew(a));
                var Success = false;

                try
                {
                    Server.Bindings           = s.Bindings.Select(b => new IPEndPoint(IPAddress.Parse(b.IpAddress), b.Port)).ToArray();
                    Server.SessionIdleTimeout = s.SessionIdleTimeout;
                    Server.UnauthenticatedSessionIdleTimeout = s.UnauthenticatedSessionIdleTimeout;
                    Server.MaxConnections          = s.MaxConnections;
                    Server.MaxConnectionsPerIP     = s.MaxConnectionsPerIP;
                    Server.MaxUnauthenticatedPerIP = s.MaxUnauthenticatedPerIP;
                    Server.MaxBadCommands          = s.MaxBadCommands;

                    Server.TimeoutCheckPeriod = s.TimeoutCheckPeriod;

                    Server.Start();

                    Console.WriteLine(@"UDP/{0}服务器已启动。结点: {1}".Formats(s.SerializationProtocolType.ToString(), String.Join(", ", Server.Bindings.Select(b => b.ToString() + "(UDP)"))));

                    Success = true;
                }
                finally
                {
                    if (!Success)
                    {
                        Server.Dispose();
                    }
                }

                return(Server);
            }
            else if (pc.OnHttp)
            {
                var s = pc.Http;

                Func <ISessionContext, KeyValuePair <IServerImplementation, IHttpVirtualTransportServer> > VirtualTransportServerFactory = Context =>
                {
                    var p    = ServerContext.CreateServerImplementationWithJsonAdapter(Factory, Context);
                    var si   = p.Key;
                    var a    = p.Value;
                    var jhps = new JsonHttpPacketServer(a, CommandName => true);
                    return(new KeyValuePair <IServerImplementation, IHttpVirtualTransportServer>(si, jhps));
                };

                var Server  = new HttpServer(ServerContext, VirtualTransportServerFactory, a => Factory.StartNew(a), a => PurifierFactory.StartNew(a));
                var Success = false;

                try
                {
                    Server.Bindings           = s.Bindings.Select(b => b.Prefix).ToArray();
                    Server.SessionIdleTimeout = s.SessionIdleTimeout;
                    Server.UnauthenticatedSessionIdleTimeout = s.UnauthenticatedSessionIdleTimeout;
                    Server.MaxConnections          = s.MaxConnections;
                    Server.MaxConnectionsPerIP     = s.MaxConnectionsPerIP;
                    Server.MaxUnauthenticatedPerIP = s.MaxUnauthenticatedPerIP;
                    Server.MaxBadCommands          = s.MaxBadCommands;

                    Server.TimeoutCheckPeriod = s.TimeoutCheckPeriod;
                    Server.ServiceVirtualPath = s.ServiceVirtualPath;

                    Server.Start();

                    Console.WriteLine(@"HTTP/{0}服务器已启动。结点: {1}".Formats("Json", String.Join(", ", Server.Bindings.Select(b => b.ToString()))));

                    Success = true;
                }
                finally
                {
                    if (!Success)
                    {
                        Server.Dispose();
                    }
                }

                return(Server);
            }
            else if (pc.OnHttpStatic)
            {
                var s = pc.HttpStatic;

                var Server  = new StaticHttpServer(ServerContext, a => Factory.StartNew(a), 8 * 1024);
                var Success = false;

                try
                {
                    Server.Bindings                = s.Bindings.Select(b => b.Prefix).ToArray();
                    Server.SessionIdleTimeout      = Math.Min(s.SessionIdleTimeout, s.UnauthenticatedSessionIdleTimeout);
                    Server.MaxConnections          = s.MaxConnections;
                    Server.MaxConnectionsPerIP     = s.MaxConnectionsPerIP;
                    Server.MaxBadCommands          = s.MaxBadCommands;
                    Server.MaxUnauthenticatedPerIP = s.MaxUnauthenticatedPerIP;

                    Server.ServiceVirtualPath = s.ServiceVirtualPath;
                    Server.PhysicalPath       = s.PhysicalPath;
                    Server.Indices            = s.Indices.Split(',').Select(Index => Index.Trim(' ')).Where(Index => Index != "").ToArray();

                    Server.Start();

                    Console.WriteLine(@"HTTP静态服务器已启动。结点: {0}".Formats(String.Join(", ", Server.Bindings.Select(b => b.ToString()))));

                    Success = true;
                }
                finally
                {
                    if (!Success)
                    {
                        Server.Dispose();
                    }
                }

                return(Server);
            }
            else
            {
                throw new InvalidOperationException("未知服务器类型: " + pc._Tag.ToString());
            }
        }
Exemplo n.º 6
0
        public void Start(int port)
        {
            using (var server = new TcpServer(IPAddress.Any, port))
            {
                server.OnDataReceived += async(sender, stream) =>
                {
                    BinaryReader  reader  = new BinaryReader(stream);
                    RequestOpcode request = (RequestOpcode)reader.ReadByte();
                    byte[]        guidBytes;
                    Guid          id;

                    switch (request)
                    {
                    case RequestOpcode.JobRequest:
                        guidBytes = reader.ReadBytes(16);
                        id        = new Guid(guidBytes);

                        BinaryWriter writer = new BinaryWriter(stream);

                        if (finished ||
                            prefixes.All(x => x.Value != null &&
                                         DateTime.Now - x.Value.LastActivity < timeout))
                        {
                            Console.WriteLine($"No more jobs for {id}");
                            writer.Write(0);
                            return;
                        }

                        var prefix = prefixes.First(x => x.Value == null ||
                                                    DateTime.Now - x.Value.LastActivity >= timeout).Key;
                        prefixes[prefix] = new AssociatedClient(id, DateTime.Now);

                        if (prefix == "")
                        {
                            writer.Write(-PerClientLength);
                        }
                        else
                        {
                            writer.Write(PerClientLength);
                        }

                        writer.Write(prefix);
                        writer.Write(desiredHash.Length);
                        writer.Write(desiredHash);

                        Console.WriteLine($"Client {id} connected, given job \"{prefix}\"");

                        break;

                    case RequestOpcode.HashNotFound:
                        guidBytes = reader.ReadBytes(16);
                        id        = new Guid(guidBytes);

                        Console.WriteLine($"Client {id} finished, hash not found");

                        if (prefixes.Any(p => p.Value != null && p.Value.guid == id))
                        {
                            var    tmp       = prefixes.FirstOrDefault(p => p.Value.guid == id);
                            string hisPrefix = tmp.Key;
                            prefixes.Remove(hisPrefix);

                            if (prefixes.Count == 0)
                            {
                                Console.WriteLine("All prefixes checked, no result found");
                                finished = true;
                                await Task.Delay(timeout);

                                server.Stop();
                            }
                        }
                        break;

                    case RequestOpcode.HashFound:
                        string result = reader.ReadString();
                        Console.WriteLine($"Result found, string: {result}");
                        Console.WriteLine("Waiting for all the clients to finish");
                        finished = true;

                        await Task.Delay(timeout);

                        while (prefixes.Any(x => x.Value != null &&
                                            DateTime.Now - x.Value.LastActivity < timeout))
                        {
                            await Task.Delay(1000);

                            Console.WriteLine("Waiting..");
                        }

                        server.Stop();
                        Console.WriteLine("Stopping..");
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                };

                Task serverTask = server.StartAsync();
                Console.WriteLine("Server started, listening to incoming connections");
                serverTask.Wait();
                Console.WriteLine("Server stopped");
            }
        }
 public ChatSession(TcpServer server) : base(server)
 {
 }
 public MathOperationMessageParse(TcpServer server)
 {
     tcpServer = server;
 }