public static void RunMainTests(string[] args) { int port = 5556; TcpListener ss = new TcpListener(IPAddress.Any, port); ss.Start(); Stream stdout = Console.OpenStandardOutput(); try { while (true) { TcpClient s = ss.AcceptTcpClient(); Console.WriteLine("--------------------------------------------------------------------------------"); Console.WriteLine("Accepted " + s); ServerThread st = new ServerThread(s, stdout); Thread t = new Thread(new ThreadStart(st.Run)); t.Start(); } } finally { ss.Stop(); } }
static void RunTest () { // Start the server thread ServerThread serverThread = new ServerThread (); serverThread.Start (); // Create the client HttpWebRequest rq = (HttpWebRequest) WebRequest.Create ("http://" + IPAddress.Loopback.ToString () + ":54321"); rq.ProtocolVersion = HttpVersion.Version11; rq.KeepAlive = false; // Get the response HttpWebResponse rsp = (HttpWebResponse) rq.GetResponse (); ASCIIEncoding enc = new ASCIIEncoding (); StringBuilder result = new StringBuilder (); // Stream the body in 1 byte at a time byte [] bytearr = new byte [1]; Stream st = rsp.GetResponseStream (); while (true) { int b = st.Read (bytearr, 0, 1); if (b == 0) { break; } result.Append (enc.GetString (bytearr)); } Assert.AreEqual ("012345670123456789abcdefabcdefghijklmnopqrstuvwxyz", result.ToString (), "#1"); }
public void ListenTest() { var t = new ServerThread(); t.Start(); Assert.Fail(); }
protected override void stopGameHandler(UserThread client, CSMessage msg) { try { ServerThread cl1 = (ServerThread)client; if (cl1.playing()) { ServerThread cl2 = cl1.CurrentChallenger; if (cl2.playing()) { msg.add(MessageType.USER, cl1.ClientUser); cl2.send(msg); } cl2.CurrentChallenger = null; cl1.CurrentChallenger = null; if (view != null && view.isOpened()) { view.removeParty(cl1.ClientUser, cl2.ClientUser); } broadcast(); } } catch (Exception e) { log(Severiry.ERROR, "Controller[STOPGAME] - " + e.Message); } }
static void Main(string[] args) { ILogger logger = new NLogger(); // Create the threads. ServerThread server = new ServerThread(logger); ListenThread listen = new ListenThread(logger, server, 4530); DatabaseThread database = new DatabaseThread(logger); // Create the login handler. Login login = new Login(logger, server, database); // Start things up. server.Run(); listen.Run(); database.Run(); // We could potentially make this a service so there's no infinite // looping. while (true) { if (server.Fatal || listen.Fatal) { // TODO: Potentially attempt to restart? break; } Thread.Sleep(100); } }
/// <summary> /// Handle the stop server event. /// </summary> private void stopServer() { CSMessage msg = new CSMessage(MessageType.DECONNECTION); broadcast(msg); foreach (UserThread cl in clients) { cl.stop(); } clients.Clear(); if (ps.isStarted()) { ps.stop(); } if (view != null && view.isOpened()) { view.clearAll(); view.updateState(ps.isStarted()); ServerThread.initCounter(); } else { manager.close(); } }
private void onClientAccept(IAsyncResult result) { TcpClient c = tcpServer.EndAcceptTcpClient(result); ServerThread.Queue(completeAcceptClient, c); tcpServer.BeginAcceptTcpClient(onClientAccept, null); }
public void makeme(ServerThread thread, byte[] packet) { this.thread = thread; _packet = packet; _offset = 1; read(); }
void Awake() { setLog (); Texture2D ci = (Texture2D)Resources.Load("CorrectSelection", typeof(Texture2D)); Texture2D ii = (Texture2D)Resources.Load("IncorrectSelection", typeof(Texture2D)); correctSelectionIndicator = ci.GetPixels (); incorrectSelectionIndicator = ii.GetPixels(); blackTexture = new Color[width*height]; for(int i =0; i< width*height; i++) { blackTexture[i] = Color.black; } sys = GameObject.Find("System"); mainScript = sys.GetComponent<MainScript>(); ServerThread server = new ServerThread(); Thread st = new Thread(new ThreadStart(server.startServer)); st.Start(); Debug.Log("Started Server"); OSCPhaseSpaceThread oscPSClient = new OSCPhaseSpaceThread(); Thread oscPSt = new Thread(new ThreadStart(oscPSClient.startServer)); oscPSt.Start(); Debug.Log("Started OSC Client"); OSCThread oscClient = new OSCThread(); Thread osct = new Thread(new ThreadStart(oscClient.startServer)); osct.Start(); }
private void processTick(object[] args) { // Check if any clients have timed out foreach (Client c in clients) { if (c.CurrentState == ConnectionState.Play) { // TODO: Check for keep alive timeouts } else { if ((DateTime.Now - c.CreationTime) >= TimeoutPeriod) { ServerThread.Queue((object[] a) => { c.Disconnect(DisconnectReason.TimedOutDuringHandshakeOrLogin); }); } } } TimeSpan sinceLastTick = DateTime.Now - lastTick; TickInfo ti = new TickInfo(); ti.TimeSinceLastTick = sinceLastTick; OnServerTick?.Invoke(ti); lastTick = DateTime.Now; }
static void Main(string[] args) { thread = new ServerThread(8989); thread.Start(); Console.ReadKey(); thread.Stop(); }
public void Listen() { // check if we aren't listening already if (m_listener != null) { throw new Exception("Server is already listening"); } // register interrupt signal handler Console.CancelKeyPress += new ConsoleCancelEventHandler(Cancel); // listen at the specified IP and port m_listener = new TcpListener(m_address, m_port); m_listener.Start(); Console.WriteLine("Listening..."); while (true) { // wait for incoming client request (blocking call) TcpClient client = m_listener.AcceptTcpClient(); // setup manual reset event ManualResetEvent mre = new ManualResetEvent(false); m_e_manualReset.Add(mre); // create new client handling thread ServerThread thread = new ServerThread(client, mre); // queue thread in thread pool ThreadPool.QueueUserWorkItem(thread.Routine); } }
IEnumerator RunServer() { UnityEngine.Debug.Log("starting server thread"); _server = new ServerThread(); _server.Start(); yield return(null); }
private void Listen() { try { Listener = new TcpListener(IP, Port); Listener.Start(); while (Run) { // get current curson pos int cursorTop = Console.CursorTop; int cursorLeft = Console.CursorLeft; Console.SetCursorPosition(0, 0); Console.WriteLine("Waiting for connection..."); // reset curson pos Console.SetCursorPosition(cursorLeft, cursorTop); TcpClient tcpC = Listener.AcceptTcpClient(); User user = RecieveUserData(tcpC.GetStream()); if (user != null) { NTClient client = new NTClient(this, tcpC, user); ClientList.Add(client); Console.SetCursorPosition(0, 1); Console.WriteLine("{0} connected!", tcpC.Client.ToString()); // reset curson pos Console.SetCursorPosition(cursorLeft, cursorTop); if (ClientList.Count == 2) { PairClients(); } } else { Console.SetCursorPosition(0, 1); Console.WriteLine("Client rejected. Could not resolve client user data..."); Console.SetCursorPosition(cursorLeft, cursorTop); tcpC?.Close(); } } } catch (Exception e) { Console.WriteLine(e.Message); } finally { Listener?.Stop(); KillClients(); ServerThread.Abort(); } }
public void Dispose() { if (ServerThread.IsAlive) { ServerThread.Abort(); } }
public static ServerThread getInstance() { if (Instance == null) { Instance = new ServerThread(); } return(Instance); }
private void Start() { //開始連線,設定使用網路、串流、TCP //Debug.Log("Hello world!"); inputBuffer = new List <string> (); st = new ServerThread(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, "0.0.0.0", 8000); st.Listen(); //讓Server socket開始監聽連線 st.StartConnect(); //開啟Server socket }
// Use this for initialization void Start() { if (serverThread == null) { //启动服务器线程 serverThread = ServerThread.getInstance(); } StartCoroutine("InitData"); StartCoroutine(UnLoad()); }
public void Dispose() { for (int i = 0; i < clientHandlers.Count; i++) { clientHandlers[i].Dispose(); } serverSocket.Dispose(); ServerThread.Abort(); GC.SuppressFinalize(this); }
protected override void endGameHandler(UserThread client, CSMessage msg) { try { ServerThread cl1 = (ServerThread)client; ServerThread cl2 = cl1.CurrentChallenger; CSMessage msg2 = new CSMessage(MessageType.END_GAME). add(MessageType.GAME_STUFF, msg.get(MessageType.GAME_STUFF)); bool play = new Random().Next(2) != 0; if (msg.get(MessageType.WIN_GAME) != null) { cl1.ClientUser.win(); msg2.add(MessageType.LOSE_GAME, true); } if (msg.get(MessageType.DRAW_GAME) != null) { cl1.ClientUser.draw(); cl2.ClientUser.draw(); msg2.add(MessageType.DRAW_GAME, true); } cl1.ClientUser.incrementParties(); cl2.ClientUser.incrementParties(); if (cl1.isLogged()) { manager.update(cl1.ClientUser); } if (cl2.isLogged()) { manager.update(cl2.ClientUser); } if (view != null && view.isOpened()) { view.update(cl1.ClientUser.Login, cl1.ClientUser); } if (view != null && view.isOpened()) { view.update(cl2.ClientUser.Login, cl2.ClientUser); } msg.add(MessageType.USER, cl2.ClientUser); msg.add(MessageType.PLAY_GAME, play); msg2.add(MessageType.USER, cl1.ClientUser); msg2.add(MessageType.PLAY_GAME, !play); cl1.send(msg); cl2.send(msg2); } catch (Exception e) { log(Severiry.ERROR, "Controller[ENDGAME] - " + e.Message); } }
/// <summary> /// Stops the socket server. /// </summary> public void Stop() { if (TcpServer != null) { TcpServer.Stop(); TcpServer = null; } State = InspectionEngineState.NotRunning; ServerThread.Abort(); }
public RequestLoginAuth(IServiceProvider serviceProvider, Packet p, ServerThread server) : base(serviceProvider) { _thread = server; _port = p.ReadShort(); _host = p.ReadString().ToLower(); _info = p.ReadString().ToLower(); _code = p.ReadString().ToLower(); _curp = p.ReadInt(); _maxp = p.ReadShort(); _gmonly = p.ReadByte(); _test = p.ReadByte(); }
private void Start() { ss.a = 1; ss.b = 2; //開始連線,設定使用網路、串流、TCP // st = new ServerThread(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, "127.0.0.1", 8000); st = new ServerThread(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, PlayerParam.ipAddress, 8000); st.Listen(); //讓Server socket開始監聽連線 st.StartConnect(); //開啟Server socket isSend = true; }
public static void Handle(Packet packet, ServerThread client) { Log.Info($"Received packet with Opcode:{packet.FirstOpcode.ToString("X2")}"); if (!ClientPacketsServ.ContainsKey(packet.FirstOpcode)) { return; } PacketBase incPacket = (PacketBase)Activator.CreateInstance(ClientPacketsServ[packet.FirstOpcode], packet, client); incPacket?.RunImpl(); }
/// <summary> /// Send the abort message form the given user 'from' to the given user 'to'. /// </summary> /// <param name="to"></param> /// <param name="from"></param> private void abortRequest(CSUser to, CSUser from) { ServerThread cl = findClient(to); if (cl != null) { CSMessage msg = new CSMessage(MessageType.CHALLENGING) .add(MessageType.ABORT, true) .add(MessageType.USER, from); cl.send(msg); cl.To = null; } }
public void Handle(Packet packet, ServerThread client) { Log.Debug($"Received packet with Opcode:{packet.FirstOpcode:X2}"); if (!ServerPackets.ContainsKey(packet.FirstOpcode)) { Log.Debug("Unknown packet opcode!"); return; } PacketBase incPacket = (PacketBase)Activator.CreateInstance(ServerPackets[packet.FirstOpcode], _serviceProvider, packet, client); incPacket?.RunImpl(); }
static void Main(string[] args) { // Obtener el puerto desde las configuraciones para escribirlo en consola mas tarde string puerto = ConfigurationManager.AppSettings["port"]; // Iniciar el procedimiento del lanzamiento del hilo servidor ServerThread server = new ServerThread(); Thread hiloNuevoServidor = new Thread(new ThreadStart(server.Execute)); // indicar método que se ejecutará al iniciar el hilo hiloNuevoServidor.IsBackground = true; hiloNuevoServidor.Start(); Console.ReadKey(); }
public ApplicationPresenter() { var settings = LoadSettings(); #pragma warning disable CA2000 // Dispose objects before losing scope DistLogger logger = new DistLogger(@"c:\work\DistCalc.Server.Log.sqlite", "Log", null); #pragma warning restore CA2000 // Dispose objects before losing scope #pragma warning disable CA2000 // Dispose objects before losing scope DistLogger errorlogger = new DistLogger(@"c:\work\DistCalc.Server.CalcErrors.sqlite", "Log", null); #pragma warning restore CA2000 // Dispose objects before losing scope ServerThread = new ServerThread(settings, new ThreadId("Server", 1), logger, errorlogger); //AutoClosingMessageBox.Show("Starting the server", "ServerStart", 5000); var t = new Thread(() => ServerThread.Run(ShowMessageBox)); t.Start(); }
/// <summary> /// Stops the server if it is running /// </summary> public void Stop() { Status = ServerStatus.Stopped; Enabled = false; // Disconnect all of the players ServerDirector.DisconnectAll(); // Close our network connection Socket.Close(); // Socket = null; // Kill the server thread ServerThread.Abort(); }
public void Stop() { LogTo.Info("Stopping media proxy server"); IsRunning = false; ServerThread?.Join(); try { Http.Stop(); Http.ClearPrefixes(); } catch (Exception ex) { LogTo.WarnException("Error while shutting down http listener", ex); } }
public void StartServer() { /*ServerSocket.Bind(new IPEndPoint(IPAddress.Any, ServerPort)); * ServerSocket.Listen(0); * ServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);*/ ServerRunning = true; server = new TcpListener(IPAddress.Any, ServerPort); listenerThread = new Thread(Listen); listenerThread.Priority = ThreadPriority.Normal; listenerThread.IsBackground = true; listenerThread.Start(); LaunchDatabaseUpdate(); // Start up threads WorldThread worldThread = new WorldThread(Database.Instance, this); ServerThread serverThread = new ServerThread(Database.Instance, this); }
public static void Main(string[] args) { int port = 5556; TcpListener ss = new TcpListener(IPAddress.Any, port); ss.Start(); Stream stdout = Console.OpenStandardOutput(); while (true) { TcpClient s = ss.AcceptTcpClient(); Console.WriteLine("--------------------------------------------------------------------------------"); Console.WriteLine("Accepted " + s); ServerThread st = new ServerThread(s, stdout); Thread t = new Thread(new ThreadStart(st.Run)); t.Start(); } }
/// <summary> /// Comienza el hilo del servidor. /// </summary> private static void StartServerThread() { if (serverThread != null) { serverThread.Server.Close(); serverThread.Abort = true; } int puerto = Convert.ToInt32(ConfigurationManager.AppSettings["port"]); serverThread = new ServerThread(puerto);; Thread t = new Thread(new ThreadStart(serverThread.StartServer));; ConsoleUtils.WriteLineWithColor("Iniciando el hilo del servidor...", ConsoleColor.Yellow); t.IsBackground = true; t.Start(); }
protected override void deconnectionHandler(UserThread client) { if (!ps.isStarted()) { return; } try { ServerThread cl1 = (ServerThread)client; if (cl1.playing()) { ServerThread cl2 = cl1.CurrentChallenger; CSMessage msg = new CSMessage(MessageType.STOP_GAME).add(MessageType.USER, cl1.ClientUser); cl2.send(msg); cl2.CurrentChallenger = null; cl1.CurrentChallenger = null; if (view != null && view.isOpened()) { view.removeParty(cl1.ClientUser, cl2.ClientUser); } } else { abortRequest(client, client.ClientUser); foreach (CSUser u in client.Froms) { abortRequest(u, client.ClientUser); } } if (view != null && view.isOpened()) { view.delete(cl1.ClientUser); } cl1.stop(); clients.Remove(cl1); broadcast(); } catch (Exception e) { log(Severiry.ERROR, "Controller[DECONNECTION] - " + e.Message); } }
public ServerTest() { _server = new PlanetServer(); _server.EventDispatcher.ConnectionEvent += OnConnection; _server.EventDispatcher.ConnectionLostEvent += OnConnectionLost; _server.EventDispatcher.LoginEvent += OnLogin; _server.EventDispatcher.ExtensionEvent += OnResponse; _server.Connect("127.0.0.1", 8000); ServerThread worker = new ServerThread(_server); Thread thread = new Thread(worker.Update); while (!thread.IsAlive) { worker.Update(); Thread.Sleep(1); } }
protected override void onCreate(Bundle savedInstanceState) { base.onCreate(savedInstanceState); var r = new System.Random(); var port = r.Next(1024, 32000); var uri = "http://" + getLocalIpAddress(); uri += ":"; uri += ((object)(port)).ToString(); this.setTitle((java.lang.CharSequence)(object)uri); serverThread = new ServerThread { mycontext = this, port = port }; new Thread(serverThread).start(); // http://stackoverflow.com/questions/8955228/webview-with-an-iframe-android // http://www.chrisdanielson.com/tag/webviewclient/ this.alertDialog = new AlertDialog.Builder(this).create(); this.progressBar = ProgressDialog.show(this, (CharSequence)(object)"look here!", (CharSequence)(object)"Loading..."); this.webview = new WebView(this); setContentView(webview); //webview.getSettings().setSupportZoom(true); webview.getSettings().setLoadsImagesAutomatically(true); webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setBuiltInZoomControls(true); //webview.setInitialScale(1); webview.setWebViewClient(new MyWebViewClient { __this = this }); webview.getSettings().setSupportZoom(false); webview.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY); //webview.getSettings().setJavaScriptEnabled(true); // no flash in emulator? // works on my phone! // no Flash since android 4.1.0!!! //webview.getSettings().setPluginsEnabled(true); //webview.getSettings().setPluginState(android.webkit.WebSettings.PluginState.ON); // OR, you can also load from an HTML string: //var summary = "<html><body>You scored <b>192</b> points.</body></html>"; //webview.loadData(summary, "text/html", null); //Log.i(TAG, "loadUrl"); webview.loadUrl(uri); //this.setContentView(sv); }
/// <summary> /// Takes the configuration info, and begins the threading /// model to take care of all the Server objects created. /// </summary> private void StartServerThreads() { //Make sure the file system environment is set up for the servers: if ( !Directory.Exists( "userdb" ) ) Directory.CreateDirectory( "userdb" ); if ( !Directory.Exists( "logs" ) ) Directory.CreateDirectory( "logs" ); if ( !Directory.Exists( "modules" ) ) Directory.CreateDirectory( "modules" ); Configuration.ServerConfig[] list = config.Servers; WriteLogFunction wlf = new WriteLogFunction( WriteLog ); bool allServersReady = true; //Loads & Initializes all servers. for ( int i = 0; i < list.Length; i++ ) { Server s = new Server( list[i], wlf ); Thread t = new Thread( s.Connect ); servers[i] = new ServerThread( s, t ); servers[i].LoadModules = s.Init(); allServersReady = allServersReady && servers[i].LoadModules; } //Load all modules. WriteLog( "Loading Modules..." ); LoadModules( config.Modules ); //Activate all the modules. for ( int m = 0; m < MaxModules; m++ ) { if ( modules[m] == null ) continue; WriteLog( " Module Loaded: " + modules[m].ModuleConfig.FullName ); for ( int s = 0; s < MaxServers; s++ ) { if ( servers[s] == null || !servers[s].LoadModules || !modules[m].ModuleConfig.QueryServerList( servers[s].Server.Config.Name ) ) continue; modules[m].Activate( s ); WriteLog( " Activated Link: " + servers[s].Server.Config.Name + "." + modules[m].ModuleConfig.FullName ); } if ( allServersReady ) { WriteLog( " Activation Completed: " + modules[m].ModuleConfig.FullName ); modules[m].ActivationComplete(); } } foreach ( ServerThread st in servers ) if ( st == null ) continue; else st.Thread.Start(); }