/// <summary> /// 开始服务 /// </summary> public void Start() { #region 创建图片文件夹 System.IO.DirectoryInfo dInfo = new System.IO.DirectoryInfo(System.Windows.Forms.Application.StartupPath +"\\Images"); if (!dInfo.Exists) dInfo.Create(); #endregion if (Images == null) Images = new Dictionary<string, ServerImage>(); if (TimerImageServer == null) { TimerImageServer = new System.Timers.Timer(); TimerImageServer.Elapsed += new System.Timers.ElapsedEventHandler(TimerImageServer_Elapsed); } TimerImageServer.Interval = 60000;//设置图片文件缓存时间 (默认1分钟) TimerImageServer.Enabled = true;//开始服务 if (tcpFileServer == null) { tcpFileServer = new TCPServer(); tcpFileServer.SessionCreated += new EventHandler<TCP_ServerSessionEventArgs<TCPServerSession>>(tcpFileServer_SessionCreated); tcpFileServer.Bindings = new IPBindInfo[] { new IPBindInfo("127.0.0.1", BindInfoProtocol.TCP, IPAddress.Any, port) }; } tcpFileServer.Start(); }
private static void Main() { Lua.DoFile(@"P:\XinFeiFei\gameres\addons\DefineText.lua"); Lua.DoFile(@"P:\XinFeiFei\gameres\addons\jobs.lua"); Lua.DoFile(@"P:\XinFeiFei\gameres\addons\propItem.lua"); ItemData = Lua.GetTable("propItem"); Console.WriteLine("Data loaded!"); Database = new FFModelContainer(ConfigurationManager.ConnectionStrings["FFModelContainer"].ConnectionString); AppDomain.CurrentDomain.ProcessExit += (EventHandler)((sender, args) => Database.SaveChanges()); new Thread(() => { while (Database != null) { Database.SaveChanges(); Thread.Sleep(Constants.DatabaseUpdateInterval); } }).Start(); var server = new TCPServer<FFConnection>(); server.Listen("127.0.0.1", 9111); }
public static void Main() { DataRecord.DataRecordGenerator drg = new DataRecord.DataRecordGenerator(); DataRecord.DataRecordPool drp = new DataRecord.DataRecordPool(drg); TCPServer serv = new TCPServer(); serv.StartServer(); Patient.Patient patient = new Patient.Patient(serv); System.Console.WriteLine("Waiting for patient"); patient.waitForPatient(); drg.registerPatient(patient); System.Console.WriteLine("Patient acquired."); drg.registerDevice(new Device.PulseOx(0)); drg.registerDevice(new Device.Zigfu(serv)); drg.registerAlgorithm(new Algorithm.Met()); drg.registerAlgorithm(new Algorithm.ExerciseAdherence()); Client.Zigfu client = new Client.Zigfu(serv); Client.Indivo ind = new Client.Indivo(serv); client.attachToPool(drp); ind.attachToPool(drp); drg.startGenerating(); while(Console.ReadKey(true).Key != ConsoleKey.Escape){ } drg.stopGenerating(); drp.destroyPool(); System.Environment.Exit(0); // Needed to kill TCPServer }
/// <summary> /// Create a new TCP connection. /// </summary> public TCPConnection(TCPServer TCPServer, TcpClient TCPClient) : base(new IPSocket(new IPv4Address(( TCPClient.Client.LocalEndPoint as IPEndPoint).Address), new IPPort ((UInt16) (TCPClient.Client.LocalEndPoint as IPEndPoint).Port)), new IPSocket(new IPv4Address(( TCPClient.Client.RemoteEndPoint as IPEndPoint).Address), new IPPort ((UInt16) (TCPClient.Client.RemoteEndPoint as IPEndPoint).Port))) { this._TCPServer = TCPServer; this._ServerTimestamp = DateTime.Now; this.TCPClient = TCPClient; this.ConnectionId = TCPServer.ConnectionIdBuilder(this, this._ServerTimestamp, base.LocalSocket, base.RemoteSocket); this._IsClosed = false; this.Stream = TCPClient.GetStream(); //_TCPClient.ReceiveTimeout = (Int32) ConnectionTimeout.TotalMilliseconds; //_TCPConnection.Value.ReadTimeout = ClientTimeout; //_TCPConnection.Value.StopRequested = false; #if __MonoCS__ // Code for Mono C# compiler #else Thread.CurrentThread.Name = (TCPServer.ConnectionThreadsNameBuilder != null) ? TCPServer.ConnectionThreadsNameBuilder(this, this._ServerTimestamp, base.LocalSocket, base.RemoteSocket) : "TCP connection from " + base.RemoteSocket.IPAddress.ToString() + ":" + base.RemoteSocket.Port.ToString(); #endif }
public static void Main() { TCPServer server = new TCPServer("127.0.0.1", 13000); server.Open(); server.ListenForClients(); server.HandleClientComm(); }
public static void Main(string[] args) { serv = new TCPServer(); serv.DataManager+= new DataManager(MainClass.OnDataReceived); serv.StartServer(); do{ }while(true); }
internal KRPCServer(IPAddress address, ushort rpcPort, ushort streamPort, bool oneRPCPerUpdate = false, uint maxTimePerUpdate = 5000, bool adaptiveRateControl = true, bool blockingRecv = true, uint recvTimeout = 1000) { rpcTcpServer = new TCPServer ("RPCServer", address, rpcPort); streamTcpServer = new TCPServer ("StreamServer", address, streamPort); rpcServer = new RPCServer (rpcTcpServer); streamServer = new StreamServer (streamTcpServer); clientScheduler = new RoundRobinScheduler<IClient<Request,Response>> (); continuations = new List<RequestContinuation> (); streamRequests = new Dictionary<IClient<byte,StreamMessage>,IList<StreamRequest>> (); OneRPCPerUpdate = oneRPCPerUpdate; MaxTimePerUpdate = maxTimePerUpdate; AdaptiveRateControl = adaptiveRateControl; BlockingRecv = blockingRecv; RecvTimeout = recvTimeout; // Tie events to underlying server rpcServer.OnStarted += (s, e) => { if (OnStarted != null) OnStarted (this, EventArgs.Empty); }; rpcServer.OnStopped += (s, e) => { if (OnStopped != null) OnStopped (this, EventArgs.Empty); }; rpcServer.OnClientRequestingConnection += (s, e) => { if (OnClientRequestingConnection != null) OnClientRequestingConnection (s, e); }; rpcServer.OnClientConnected += (s, e) => { if (OnClientConnected != null) OnClientConnected (s, e); }; rpcServer.OnClientDisconnected += (s, e) => { if (OnClientDisconnected != null) OnClientDisconnected (s, e); }; // Add/remove clients from the scheduler rpcServer.OnClientConnected += (s, e) => clientScheduler.Add (e.Client); rpcServer.OnClientDisconnected += (s, e) => clientScheduler.Remove (e.Client); // Add/remove clients from the list of stream requests streamServer.OnClientConnected += (s, e) => streamRequests [e.Client] = new List<StreamRequest> (); streamServer.OnClientDisconnected += (s, e) => streamRequests.Remove (e.Client); // Validate stream client identifiers streamServer.OnClientRequestingConnection += (s, e) => { if (rpcServer.Clients.Where (c => c.Guid == e.Client.Guid).Any ()) e.Request.Allow (); else e.Request.Deny (); }; }
internal KRPCServer(IPAddress address, ushort rpcPort, ushort streamPort) { rpcTcpServer = new TCPServer ("RPCServer", address, rpcPort); streamTcpServer = new TCPServer ("StreamServer", address, streamPort); rpcServer = new RPCServer (rpcTcpServer); streamServer = new StreamServer (streamTcpServer); clientScheduler = new RoundRobinScheduler<IClient<Request,Response>> (); continuations = new List<RequestContinuation> (); streamRequests = new Dictionary<IClient<byte,StreamMessage>,IList<StreamRequest>> (); // Tie events to underlying server rpcServer.OnStarted += (s, e) => { if (OnStarted != null) OnStarted (this, EventArgs.Empty); }; rpcServer.OnStopped += (s, e) => { if (OnStopped != null) OnStopped (this, EventArgs.Empty); }; rpcServer.OnClientRequestingConnection += (s, e) => { if (OnClientRequestingConnection != null) OnClientRequestingConnection (s, e); }; rpcServer.OnClientConnected += (s, e) => { if (OnClientConnected != null) OnClientConnected (s, e); }; rpcServer.OnClientDisconnected += (s, e) => { if (OnClientDisconnected != null) OnClientDisconnected (s, e); }; // Add/remove clients from the scheduler rpcServer.OnClientConnected += (s, e) => clientScheduler.Add (e.Client); rpcServer.OnClientDisconnected += (s, e) => clientScheduler.Remove (e.Client); // Add/remove clients from the list of stream requests streamServer.OnClientConnected += (s, e) => streamRequests [e.Client] = new List<StreamRequest> (); streamServer.OnClientDisconnected += (s, e) => streamRequests.Remove (e.Client); // Validate stream client identifiers streamServer.OnClientRequestingConnection += (s, e) => { if (rpcServer.Clients.Where (c => c.Guid == e.Client.Guid).Any ()) e.Request.Allow (); else e.Request.Deny (); }; }
public void StartStop () { int serverStarted = 0; int serverStopped = 0; var server = new TCPServer ("Test", IPAddress.Loopback, 0); server.OnStarted += (s, e) => serverStarted++; server.OnStopped += (s, e) => serverStopped++; Assert.IsFalse (server.Running); for (int i = 0; i < 5; i++) { server.Start (); Assert.IsTrue (server.Running); server.Stop (); Assert.IsFalse (server.Running); } Assert.AreEqual (5, serverStarted); Assert.AreEqual (5, serverStopped); Assert.AreEqual (0, server.BytesRead); Assert.AreEqual (0, server.BytesWritten); }
public void Simple() { bool serverStarted = false; bool serverStopped = false; var server = new TCPServer ("Test", IPAddress.Loopback, 0); server.OnStarted += (s, e) => serverStarted = true; server.OnStopped += (s, e) => serverStopped = true; Assert.IsFalse (server.Running); server.Start (); Assert.IsTrue (server.Running); Assert.AreEqual (0, server.Clients.Count ()); Assert.AreEqual (IPAddress.Loopback, server.Address); Assert.IsTrue (server.Port > 0); server.Stop (); Assert.IsFalse (server.Running); Assert.AreEqual (0, server.Clients.Count ()); Assert.IsTrue (serverStarted); Assert.IsTrue (serverStopped); }
public void BindToAnyAddress() { bool serverStarted = false; bool serverStopped = false; var server = new TCPServer ("Test", IPAddress.Any, 0); server.OnStarted += (s, e) => serverStarted = true; server.OnStopped += (s, e) => serverStopped = true; Assert.IsFalse (server.Running); server.Start (); Assert.IsTrue (server.Running); Assert.AreEqual (0, server.Clients.Count ()); Assert.AreEqual (IPAddress.Any, server.Address); Assert.IsTrue (server.Port > 0); server.Stop (); Assert.IsFalse (server.Running); Assert.AreEqual (0, server.Clients.Count ()); Assert.IsTrue (serverStarted); Assert.IsTrue (serverStopped); Assert.AreEqual (0, server.BytesRead); Assert.AreEqual (0, server.BytesWritten); }
public void ClientConnectAndDisconnect() { var server = new TCPServer ("Test", IPAddress.Loopback, 0); bool clientRequestingConnection = false; bool clientConnected = false; bool clientDisconnected = false; server.OnClientRequestingConnection += (s, e) => { e.Request.Allow (); clientRequestingConnection = true; }; server.OnClientConnected += (s, e) => clientConnected = true; server.OnClientDisconnected += (s, e) => clientDisconnected = true; server.Start (); var tcpClient = new TcpClient (server.Address.ToString (), server.Port); UpdateUntil (server, () => clientConnected); Assert.IsTrue (tcpClient.Connected); Assert.IsFalse (clientDisconnected); Assert.AreEqual (1, server.Clients.Count ()); tcpClient.GetStream ().Close (); tcpClient.Close (); Assert.IsFalse (tcpClient.Connected); UpdateUntil (server, () => clientDisconnected); Assert.AreEqual (0, server.Clients.Count ()); Assert.IsFalse (tcpClient.Connected); server.Stop (); Assert.IsTrue (clientRequestingConnection); Assert.IsTrue (clientConnected); Assert.IsTrue (clientDisconnected); Assert.AreEqual (0, server.BytesRead); Assert.AreEqual (0, server.BytesWritten); }
/// <summary> /// 开始服务 /// </summary> public void Start() { if (tcpMessageServer == null) { tcpMessageServer = new TCPServer(); tcpMessageServer.SessionCreated += new EventHandler<TCP_ServerSessionEventArgs<TCPServerSession>>(tcpMessageServer_SessionCreated); tcpMessageServer.Bindings = new IPBindInfo[] { new IPBindInfo("127.0.0.1", BindInfoProtocol.TCP, IPAddress.Any, port) }; } tcpMessageServer.Start(); }
public void StillPendingByDefault() { var server = new TCPServer ("Test", IPAddress.Loopback, 0); bool clientRequestingConnection = false; server.OnClientRequestingConnection += (s, e) => clientRequestingConnection = true; server.OnClientConnected += (s, e) => Assert.Fail (); server.OnClientDisconnected += (s, e) => Assert.Fail (); server.Start (); var tcpClient = new TcpClient (server.Address.ToString (), server.Port); UpdateUntil (server, () => clientRequestingConnection); Assert.IsTrue (clientRequestingConnection); Assert.AreEqual (0, server.Clients.Count ()); server.Stop (); tcpClient.Close (); Assert.AreEqual (0, server.BytesRead); Assert.AreEqual (0, server.BytesWritten); }
private static void StartServer() { serv = new TCPServer(); serv.DataManager+= new DataManager(MainClass.OnDataReceived); serv.StartServer(); Console.WriteLine("TCP Server Started::Listening to port 10000"); }
public static void Main (string[] args) { bool showHelp = false; bool showVersion = false; Logger.Enabled = true; Logger.Level = Logger.Severity.Info; RPCException.VerboseErrors = true; bool serverDebug = false; ushort rpcPort = 0; ushort streamPort = 0; string type = "protobuf"; var options = new OptionSet { { "h|help", "show this help message and exit", v => showHelp = v != null }, { "v|version", "show program's version number and exit", v => showVersion = v != null }, { "rpc-port=", "Port number to use for the RPC server. If unspecified, use an ephemeral port.", (ushort v) => rpcPort = v }, { "stream-port=", "Port number to use for the stream server. If unspecified, use an ephemeral port.", (ushort v) => streamPort = v }, { "type=", "Type of server to run. Current just 'protobuf'.", v => type = v }, { "debug", "Set log level to 'debug', defaults to 'info'", v => { if (v != null) { Logger.Enabled = true; Logger.Level = Logger.Severity.Debug; } } }, { "quiet", "Set log level to 'warning'", v => { if (v != null) { Logger.Enabled = true; Logger.Level = Logger.Severity.Warning; } } }, { "server-debug", "Output debug information about the server", v => serverDebug = v != null }, }; options.Parse (args); if (showHelp) { Help (options); return; } if (showVersion) { var assembly = Assembly.GetEntryAssembly (); var info = FileVersionInfo.GetVersionInfo (assembly.Location); var version = String.Format ("{0}.{1}.{2}", info.FileMajorPart, info.FileMinorPart, info.FileBuildPart); Console.WriteLine ("TestServer.exe version " + version); return; } KRPC.Service.Scanner.Scanner.GetServices (); var core = Core.Instance; CallContext.SetGameScene (GameScene.SpaceCenter); var timeSpan = new TimeSpan (); Core.Instance.GetUniversalTime = () => timeSpan.TotalSeconds; var rpcTcpServer = new TCPServer ("RPCServer", IPAddress.Loopback, rpcPort); var streamTcpServer = new TCPServer ("StreamServer", IPAddress.Loopback, streamPort); Server server; if (type == "protobuf") { var rpcServer = new KRPC.Server.ProtocolBuffers.RPCServer (rpcTcpServer); var streamServer = new KRPC.Server.ProtocolBuffers.StreamServer (streamTcpServer); server = new Server (rpcServer, streamServer); } else { Console.WriteLine ("Server type '" + type + "' not supported"); return; } server.OnClientRequestingConnection += (s, e) => e.Request.Allow (); Console.WriteLine ("Starting server..."); server.Start (); Console.WriteLine ("type = " + type); Console.WriteLine ("rpc_port = " + rpcTcpServer.Port); Console.WriteLine ("stream_port = " + streamTcpServer.Port); Console.WriteLine ("Server started successfully"); const long targetFPS = 60; long update = 0; long ticksPerUpdate = Stopwatch.Frequency / targetFPS; var timer = new Stopwatch (); while (server.Running) { timer.Reset (); timer.Start (); core.Update (); if (serverDebug && update % targetFPS == 0) { // Output details about whether server.Update() took too little or too long to execute var elapsed = timer.ElapsedTicks; var diffTicks = Math.Abs (ticksPerUpdate - elapsed); var diffTime = Math.Round ((double)diffTicks / (double)Stopwatch.Frequency * 1000d, 2); if (elapsed > ticksPerUpdate) Console.WriteLine ("Slow by " + diffTime + " ms (" + diffTicks + " ticks)"); else Console.WriteLine ("Fast by " + diffTime + " ms (" + diffTicks + " ticks)"); } // Wait, to force 60 FPS while (timer.ElapsedTicks < ticksPerUpdate) { } update++; } }
protected override void FireStateChanged(TCPServer.TCPServer source, string state) { if (StateChanged != null) StateChanged(this, state); }
/// <summary> /// Main. /// </summary> /// <param name="myArgs">The arguments.</param> public static void Main(String[] myArgs) { #region Start TCPServers //var _TCPServer1 = new TCPServer(new IPv4Address(new Byte[] { 192, 168, 178, 31 }), new IPPort(2001), NewConnection => // { // NewConnection.WriteToResponseStream("Hello world!" + Environment.NewLine + Environment.NewLine); // NewConnection.Close(); // }, true); //Console.WriteLine(_TCPServer1); // The first line of the repose will be served from the CustomTCPConnection handler. var _TCPServer2 = new TCPServer<CustomTCPConnection>(IPv4Address.Any, new IPPort(2002), NewConnection => { NewConnection.WriteToResponseStream("...world!" + Environment.NewLine + Environment.NewLine); NewConnection.Close(); }, true); Console.WriteLine(_TCPServer2); #endregion #region Start HTTPServers // Although the socket listens on IPv4Address.Any the service is // configured to serve clients only on http://localhost:8181 // More details within DefaultHTTPService.cs var _HTTPServer1 = new HTTPServer(IPv4Address.Any, new IPPort(8181), Autostart: true) { ServerName = "Default Hermod Demo" }; Console.WriteLine(_HTTPServer1); // This service uses a custom HTTPService defined within IRESTService.cs var _HTTPServer2 = new HTTPServer<IRESTService>(IPv4Address.Any, IPPort.HTTP, Autostart: true) { ServerName = "Customized Hermod Demo" }; Console.WriteLine(_HTTPServer2); #endregion #region UDP Servers var _UDPServer1 = new UDPServer(new IPPort(5555), NewPacket => { //NewPacket.Data = new Byte[10]; // NewPacket.Close(); }, true); #endregion var _client1 = new HTTPClient(IPv4Address.Localhost, IPPort.HTTP); var _request0 = _client1.GET("/HelloWorld"). SetHost("localhorst"). AddAccept(HTTPContentType.TEXT_UTF8, 1); var _request1 = _client1.GET("/HelloWorld"). SetHost("localhorst"). AddAccept(HTTPContentType.HTML_UTF8, 1); //WriteRequest(_request0.EntireRequestHeader); //_client1.Execute(_request0, response => WriteResponse(response.Content.ToUTF8String())). // ContinueWith(HTTPClient => { WriteRequest(_request1.EntireRequestHeader); return HTTPClient.Result; }). // ContinueWith(HTTPClient => HTTPClient.Result.Execute(_request1, response => WriteResponse(response.Content.ToUTF8String()))). // Wait(); var _client2 = new HTTPClient(IPv4Address.Parse("188.40.47.229"), IPPort.HTTP); var _requestA = _client2.GET("/"). SetProtocolVersion(HTTPVersion.HTTP_1_1). SetHost("www.ahzf.de"). SetUserAgent("Hermod HTTP Client v0.1"). SetConnection("keep-alive"). AddAccept(HTTPContentType.HTML_UTF8, 1); var _requestB = _client2.GET("/nfgj"). SetProtocolVersion(HTTPVersion.HTTP_1_1). SetHost("www.ahzf.de"). SetUserAgent("Hermod HTTP Client v0.1"). SetConnection("keep-alive"). AddAccept(HTTPContentType.HTML_UTF8, 1); WriteRequest(_requestA); _client2.Execute(_requestA, response => WriteResponse(response)). ContinueWith(Client => Client.Result.Execute(_requestB, response => WriteResponse(response))); var _req23a = new HTTPRequestBuilder(). SetHTTPMethod (HTTPMethod.GET). SetProtocolName ("µHTTP"). SetProtocolVersion (new HTTPVersion(2, 0)). SetHost ("localhorst"). SetUserAgent ("Hermod µHTTP Client"). SetContent ("This the HTTP content..."); _req23a.QueryString.Add("name", "alice"). Add("friend", "bob"). Add("friend", "carol"); var _req23b = new HTTPRequestBuilder() { HTTPMethod = HTTPMethod.GET, ProtocolName = "µHTTP", ProtocolVersion = new HTTPVersion(2, 0), Host = "localhorst", UserAgent = "Hermod µHTTP Client", Content = "This the HTTP content...".ToUTF8Bytes() }; // var Response = new TCPClientRequest("localhost", 80).Send("GETTT / HTTP/1.1").FinishCurrentRequest().Response; Console.ReadLine(); Console.WriteLine("done!"); }
/// <summary> /// 释放资源 /// </summary> public void Dispose() { if (tcpFileServer != null && tcpFileServer.IsRunning) { tcpFileServer.Stop(); tcpFileServer.Dispose(); tcpFileServer = null; } if (TimerImageServer != null) { TimerImageServer.Enabled = false;//停止文件服务检测 TimerImageServer.Dispose(); TimerImageServer = null; } if (Images != null) { Images.Clear(); Images = null; } }
private static void Do() { var server = new TCPServer(12354); server.Do(ClientHandler); }
public ServerDatabase() { TCPServer.dB = new LoginDatabase(); server = new TCPServer(); }
protected abstract void FireStateChanged(TCPServer.TCPServer source, string state);
public void TCPCommunicationEndPoint_StateChanged(TCPServer.TCPServer source, string state) { FireStateChanged(source, state); }
/// <summary> /// 释放资源 /// </summary> public void Dispose() { if (tcpMessageServer != null && tcpMessageServer.IsRunning) { tcpMessageServer.Stop(); tcpMessageServer.Dispose(); tcpMessageServer = null; } }
public ThreePhaseController(InterfaceConfiguration interfaces) { _tcpServer = new TCPServer(interfaces.TcpPort); _interfaces = interfaces; }
/* ==== METHODS ===== */ internal void Listen() { Server = new TCPServer(1338); Server.ClientConnect += Server_ClientConnect; Server.Start(); }