private void button2_Click(object sender, EventArgs e) { TcpListener serverSocket = new TcpListener(IPAddress.Any, 4955); TcpClient clientSocket = default(TcpClient); serverSocket.Start(); clientSocket = serverSocket.AcceptTcpClient(); try { NetworkStream networkStream = clientSocket.GetStream(); byte[] bytesFrom = new byte[10025]; networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize); string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom); dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$")); MessageBox.Show( dataFromClient); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public void ReceiveActions() { try { serversocket = new TcpListener(new IPEndPoint(IPAddress.Any, 1234)); serversocket.Start(); tcpP1 = serversocket.AcceptTcpClient(); NetworkStream P1stream = tcpP1.GetStream(); InstancierBateaux(p1, P1stream); WriteMessage("Premier Joueur accepté"); tcpP2 = serversocket.AcceptTcpClient(); NetworkStream P2stream = tcpP2.GetStream(); InstancierBateaux(p2, P2stream); WriteMessage("Deuxième Joueur accepté"); WriteMessage("Tous les bateaux sont prêts"); while (!end) { ReceiveAttack(p1, P2stream, P1stream); ReceiveAttack(p2, P1stream, P2stream); } } catch(Exception se) { MessageBox.Show(se.Message + " Vous avez perdu le contact avec un socket!"); } }
public void Start() { // Создаем "слушателя" для указанного порта Listener = new TcpListener(IPAddress.Any, port); Listener.Start(); // Запускаем его //Client client = new Client(Listener.AcceptTcpClient()); // В бесконечном цикле while (true) { Client client = new Client(Listener.AcceptTcpClient()); ThreadPool.QueueUserWorkItem(new WaitCallback(ClientThread), Listener.AcceptTcpClient()); if (client.GetSecondParam() != null) { JobID jId = new JobID(jobIdCount, client.GetFirstParam(), client.GetSecondParam()); jobIdCount++; jobId.Add(jId); } if (client.GetSecondParam() == null) { jid = client.GetFirstParam(); } Thread.Sleep(1000); Worker worker = new Worker(jobId, jid); Thread worker_thread = new Thread(worker.Start); worker_thread.Start(); } }
public void ProcessMsBuildLoggerMessage(ConcurrentQueue<MessageArgsLogger> messagesToBeSend, IpAddressSettings settings) { TcpListener agentMsBuildListener = null; TcpClient agentTcpMsbuildReader = null; try { agentMsBuildListener = new TcpListener(settings.GetIPAddress(), settings.Port); agentMsBuildListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); agentTcpMsbuildReader = default(TcpClient); agentMsBuildListener.Start(); agentTcpMsbuildReader = agentMsBuildListener.AcceptTcpClient(); do { string dataFromClient = ATACore.TcpWrapperProcessor.TcpClientWrapper.ReadSimpleClientMessage(agentTcpMsbuildReader); if (!String.IsNullOrEmpty(dataFromClient)) ATACore.CommandExecutor.EnqueueNewMessage(dataFromClient, MessageSource.MsBuildLogger, messagesToBeSend); else if (dataFromClient == null) agentTcpMsbuildReader = agentMsBuildListener.AcceptTcpClient(); } while (true); } catch (Exception ex) { Log.Error("Exception in ProcessClientMessge", ex); } finally { ATACore.TcpWrapperProcessor.TcpListenerWrapper.CloseTcpMsLogger(agentMsBuildListener, agentTcpMsbuildReader); } }
private ServerCore() { LoadConfig(); RegisterCommanders(); try { sqlConnecter = SqlConnector.Instance; } catch (Exception ex) { Console.WriteLine("Could not connect to Mysql: \"" + ex.Message + "\""); Console.WriteLine("Aborting. Press any key to exit"); Console.Read(); return; } idConnection = new Dictionary <UInt32, TcpClient>(); connectionWorker = new Dictionary <TcpClient, ClientWorker>(); connectionId = new Dictionary <TcpClient, UInt32>(); workers = new List <ClientWorker>(); TcpListener tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Parse(ip), port); tcpListener.Start(); while (true) { TcpClient connection = tcpListener.AcceptTcpClient(); Console.WriteLine("Someone connected"); ClientWorker worker = new ClientWorker(connection); lock (mutex) { connectionWorker.Add(connection, worker); workers.Add(worker); } } }
static private void ListenHandler() { var myIP = Communication.GetLocalIP(); var epLocal = new System.Net.IPEndPoint(myIP, TCPPort); var tcpListener = new System.Net.Sockets.TcpListener(epLocal); tcpListener.Start(); while (IsListening) { System.Threading.Thread.Sleep(1000); if (tcpListener.Pending()) { var tcpClient = tcpListener.AcceptTcpClient(); var netStream = tcpClient.GetStream(); var buffer = new byte[1024]; if (!netStream.DataAvailable) { continue; } List <byte> bufferTotal = new List <byte>(); while (netStream.DataAvailable) { netStream.Read(buffer, 0, 1024); bufferTotal.AddRange(buffer); } tcpClient.Close(); netStream.Close(); var receive = System.Text.Encoding.UTF8.GetString(bufferTotal.ToArray()); Owner.Invoke(DgGetMsg, receive); } } tcpListener.Stop(); }
public void ServerThreadProc() { while (true) { try { // 處理用戶端連線 tcpClient = tcpListener.AcceptTcpClient(); // 取得本機相關的網路資訊 IPEndPoint serverInfo = (IPEndPoint)tcpListener.LocalEndpoint; // 以Client屬性取得用戶端之Socket物件 Socket clientSocket = tcpClient.Client; // 取得連線用戶端相關的網路連線資訊 IPEndPoint clientInfo = (IPEndPoint)clientSocket.RemoteEndPoint; Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString()); Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString()); } catch (Exception ex) { Console.WriteLine(ex.StackTrace.ToString()); } } }
/// <summary> /// Thread for session with PythonServer /// </summary> private void Run() { try { // Build listener for python engine listener = new TcpListener(9669); listener.Start(); // Wait connection from python engine and if successful then create new socket to python engine pythonClient = listener.AcceptTcpClient(); mainForm.PrintToLog(DateTime.Now.ToShortTimeString() + " : Server trying start...", Color.Black); listener.Stop(); // stop listening because python engine connected to GUI flagRun = true; // Asynchronic StateObject StateObject stateObject = new StateObject(); stateObject.workSocket = pythonClient.Client; // Begins to asynchronously receive data from a connected socket with python engine pythonClient.Client.BeginReceive(stateObject.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(Read_Callback), stateObject); } catch (SocketException se) { mainForm.PrintToLog(se.Message, Color.Red); } catch (Exception e) { mainForm.PrintToLog(e.Message, Color.Red); } }
/// <summary> /// Server's main loop implementation. /// </summary> /// <param name="log"> The Logger instance to be used.</param> public void Run( Logger log ) { TcpListener srv = null; try { srv = new TcpListener( IPAddress.Loopback, portNumber ); srv.Start(); while ( true ) { log.LogMessage( "Listener - Waiting for connection requests." ); TcpClient socket = srv.AcceptTcpClient(); socket.LingerState = new LingerOption( true, 10 ); log.LogMessage( String.Format( "Listener - Connection established with {0}.", socket.Client.RemoteEndPoint ) ); // Instantiating protocol handler and associate it to the current TCP connection _dispatcher.ProcessConnection(socket.GetStream(), log); //Handler protocolHandler = new Handler( socket.GetStream(), log ); // Synchronously process requests made through de current TCP connection //Task.Factory.StartNew((handler) => ((Handler) handler).Run(), protocolHandler); //protocolHandler.Run(); Program.ShowInfo( Store.Instance ); } } finally { log.LogMessage( "Listener - Ending." ); if ( srv != null ) { srv.Stop(); } } }
public void run() { IPAddress localAdd = IPAddress.Parse(StarryboundServer.config.proxyIP); TcpListener serversocket = new TcpListener(localAdd, StarryboundServer.config.proxyPort); serversocket.Start(); StarryboundServer.logInfo("Proxy server has been started on " + localAdd.ToString() + ":" + StarryboundServer.config.proxyPort); StarryboundServer.serverState = ServerState.Running; try { while (true) { TcpClient clientSocket = serversocket.AcceptTcpClient(); new Thread(new ThreadStart(new ClientThread(clientSocket).run)).Start(); } } catch (Exception e) { StarryboundServer.logException("ListenerThread: " + e.ToString()); } serversocket.Stop(); StarryboundServer.logException("ListenerThread has failed - No new connections will be possible."); Console.ReadLine(); }
static void Listen(IPAddress ip, int port) { var listener = new TcpListener(new IPEndPoint(ip, port)); listener.Start(); using (var client = listener.AcceptTcpClient()) { using (var stream = client.GetStream()) { while (true) { var buffer = new byte[256]; var count = stream.Read(buffer, 0, buffer.Length); var data = new byte[count]; Array.Copy(buffer, data, data.Length); var text = System.Text.Encoding.Default.GetString(data); var result = text.ToUpper(); var resultBytes = System.Text.Encoding.Default.GetBytes(result); stream.Write(resultBytes, 0, resultBytes.Length); } } } }
public static void Main(string[] args) { IPAddress ip = IPAddress.Loopback; int port = 9000; byte[] buffer = new byte[256]; TcpListener server = new TcpListener (ip, port); try { server.Start (); while (true) { Console.WriteLine ("waiting for connection"); TcpClient client = server.AcceptTcpClient (); Console.WriteLine ("connected " + client.Client.AddressFamily); NetworkStream stream = client.GetStream (); // receive data from client, send responses int i; while ((i = stream.Read (buffer, 0, buffer.Length)) != 0) { HandleMessage (buffer, i); SendResponse (stream, "response"); } } } catch (SocketException e) { Console.WriteLine ("SocketException: {0}", e); } finally { server.Stop (); } }
public static void Main(string[] args) { chatrooms = new List<Chatroom> (); users = new List<User> (); Console.WriteLine ("Please enter the port for the server: "); string port = Console.ReadLine (); TcpListener serverSocket = new TcpListener (IPAddress.Loopback, Convert.ToInt32 (port)); try { serverSocket.Start (); Console.WriteLine (String.Format ("[Server started on 127.0.0.1 {0}]", port)); } catch { Console.WriteLine ("[Server failed to start]"); return; } int clientIds = 1; // create a new client when a new connection comes in, and create user entry for that client connection while (true) { TcpClient client = serverSocket.AcceptTcpClient (); User user = new User (client, clientIds); users.Add (user); clientIds++; Thread t = new Thread (new ParameterizedThreadStart (HandleClient)); t.Start (user); } }
//to get messages from server public void recieve() { TcpListener listner = new TcpListener(IPAddress.Parse(ip), portOut); while (true) { listner.Start(); TcpClient reciever = listner.AcceptTcpClient(); Stream r_stream = reciever.GetStream(); Byte[] bytes = new Byte[256]; int i; data = null; while ((i = r_stream.Read(bytes, 0, bytes.Length)) != 0) { data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); } string[] lines = Regex.Split(data, ":"); com.Invoke(new Action(() => { eval.evaluate(data, com); com.displayData("\n msg => \n" + data + "\n"); })); r_stream.Close(); listner.Stop(); reciever.Close(); } }
private void StartAccept() { t1 = new System.Threading.Thread(() => { RLib.WatchLog.Loger.Log("启动监听", ""); while (true) { try { var it = tcpl.AcceptTcpClient(); var item = TryFilter(it); if (item == null) { try { it.Close(); } catch { } } else { AddClient(item); } } catch { } System.Threading.Thread.Sleep(10); } }); t1.IsBackground = true; t1.Start(); }
public Server() { path = Directory.GetCurrentDirectory(); configFile = Path.Combine(path, "patients.json"); try { Console.WriteLine("loading session"); patients = JsonCommunication.loadPatientsJson(configFile); } catch (Exception) { Console.WriteLine("no sessions to load"); patients = new List<Patient>(); // to be replaced with list loaded from patient document } serverListener = new TcpListener(IPAddress.Any, Port); serverListener.Start(); Console.WriteLine("Server gestart, wachten op verbindingen...\r\n"); while (true) { Console.WriteLine("Wachten op verbindingen...\r\n"); TcpClient tcp = serverListener.AcceptTcpClient(); new Thread(Handler).Start(tcp); Console.WriteLine("Nieuwe verbinding geaccepteerd.\r\n"); } }
/// <summary> /// Вызовет SocketException если порт уже слушается /// </summary> /// <param name="port"></param> public void Listen(int port) { _listener = new TcpListener(IPAddress.Any,port); _listener.Start(); _client = _listener.AcceptTcpClient();//повесит программу до подключения клиента StartRecieve(); }
public Chatserver() { //create our nickname and nickname by connection variables nickName = new Hashtable(100); nickNameByConnect = new Hashtable(100); //create our TCPListener object chatServer = new System.Net.Sockets.TcpListener(4296); //check to see if the server is running //while (true) do the commands while (true) { //start the chat server chatServer.Start(); //check if there are any pending connection requests if (chatServer.Pending()) { //if there are pending requests create a new connection Chat.Sockets.TcpClient chatConnection = chatServer.AcceptTcpClient(); //display a message letting the user know they're connected Console.WriteLine("You are now connected"); //create a new DoCommunicate Object DoCommunicate comm = new DoCommunicate(chatConnection); } } }
public void FTP_Receive(string filename) { try { System.Net.IPAddress localAdd = System.Net.IPAddress.Parse(ips.AddressList[0].ToString()); System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(localAdd, FTPPORTNO); listener.Start(); TcpClient tcpClient = listener.AcceptTcpClient(); NetworkStream nws = tcpClient.GetStream(); if (File.Exists("c:\\temp\\" + filename)) { File.Delete("c:\\temp\\" + filename); } fs = new System.IO.FileStream("c:\\temp\\" + filename, FileMode.Append, FileAccess.Write); int counter = 0; int totalBytes = 0; do { int bytesRead = nws.Read(data, 0, tcpClient.ReceiveBufferSize); totalBytes += bytesRead; fs.Write(data, 0, bytesRead); ToolStripStatusLabel1.Text = "Receiving " + totalBytes + " bytes...."; Application.DoEvents(); counter += 1; } while (!(!(nws.DataAvailable))); ToolStripStatusLabel1.Text = "Receiving " + totalBytes + " bytes....Done."; fs.Close(); tcpClient.Close(); listener.Stop(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
// constructeur public FormServeur() { InitializeComponent(); Joueur1 = new Joueur(panelFond, new Point(100, 100),true); Joueur2 = new Joueur(panelFond, new Point(100, 150),false); // Cette fois les joueurs sont clairements labelScoreJ1.Text = "0"; labelScoreJ2.Text = "0"; // L'interface n'est plus la même non plus, on dédouble tout. pBChargeJ1.Maximum = 1000; pBChargeJ1.Minimum = 0; pBChargeJ2.Maximum = 1000; pBChargeJ2.Minimum = 0; try { IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //on utilise l'adresse ip locale myList = new TcpListener(ipAd, 8001); //initialisation du listener myList.Start(); // on écoute sur le port Console.WriteLine("The server is running at port 8001..."); Console.WriteLine("The local End point is :" + myList.LocalEndpoint); // Ces trois lignes ci ne servent qu'a controler via la console ce qui se passe. Console.WriteLine("Waiting for a connection....."); cl = myList.AcceptTcpClient(); // dés qu'il y a une connection on peut passer a la suite Console.WriteLine("Connection accepted from " + cl.Client.RemoteEndPoint); stm = cl.GetStream(); // le flux de données est créé } catch (Exception e) { Console.WriteLine("Error..... " + e.StackTrace); Console.ReadLine(); } th1 = new Thread(Launch); // on lance le thread qui va lire le flux th1.Name = "Serveur"; th1.Start(); }
private void ListenForClients(object olistener) { System.Net.Sockets.TcpListener listener = olistener as System.Net.Sockets.TcpListener; listener.Start(); while (!_cancelToken.IsCancellationRequested && !_shutdown) { try { //blocks until a client has connected to the server TcpClient client = listener.AcceptTcpClient(); // Wait for a client, spin up a thread. var clientThread = new Thread(new ParameterizedThreadStart(HandleNewClient)); clientThread.Start(client); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.Interrupted) { break; } } } }
public Form2(String hostPort, Form1 form1) { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // dataReadyToSend = new AutoResetEvent(false); refToForm1 = form1; // Resolve the local host. IPHostEntry localHost = Dns.Resolve(Dns.GetHostName()); // Create a local end point for listening. IPEndPoint localEndPoint = new IPEndPoint(localHost.AddressList[0], 4001); // Instantiate the TCP Listener. tcpListener = new TcpListener(localEndPoint); tcpListener.Start(); tcp = tcpListener.AcceptTcpClient(); ethernetThreadStart = new ThreadStart(this.ThreadProcPollOnEthernet); pollDevicesEthernetThread = new Thread(ethernetThreadStart); pollDevicesEthernetThread.Name = "Listener's Receive Thread"; pollDevicesEthernetThread.ApartmentState = System.Threading.ApartmentState.MTA; pollDevicesEthernetThread.Start(); }
public override void Initiate() { base.Initiate(); Console.WriteLine("Web communicator"); Console.Write("Starting socket..."); try { server = new TcpListener(IPAddress.Any, portNumber); server.Start(); } catch { Program.Shutdown("Server Startup Failed"); return; } Console.WriteLine("Done"); while (Program.Update) { TcpClient newClient = server.AcceptTcpClient(); ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessClient), newClient); } }
public void CreateTcpListener() { TcpClient client = null; NetworkStream ns = null; System.IO.StreamReader sr = null; try { listener = new System.Net.Sockets.TcpListener(ipEndPoint); listener.Start(); while (true) { client = listener.AcceptTcpClient(); ns = client.GetStream(); sr = new System.IO.StreamReader(ns); while (client.Connected) { string data = sr.ReadLine(); if (data != null) { textBox1.AppendText(data + "\r\n"); } } } } catch (Exception error) { MessageBox.Show(error.ToString()); } }
private void ServerThread() { try { while (serverFlg == true) { Console.WriteLine("ServerThread"); // ソケット接続待ち if (listener.Pending()) //接続待ちがあれば { TcpClient myTcpClient = listener.AcceptTcpClient(); // クライアントから接続有り //if(myTcpClient) // クライアント送受信オブジェクト生成 client = new ClientTcpIp(); client.objSck = myTcpClient; client.objStm = myTcpClient.GetStream(); // クライアントとの送受信開始 client.readFlg = true; if (serverFlg == true) { clientThread = new Thread( new ThreadStart(client.ReadWrite)); clientThread.Start(); } } } Console.WriteLine("STOP Server"); } catch { } }
static void Main(string[] args) { //string ipString = "127.0.0.1"; //System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString); string host = "localhost"; System.Net.IPAddress ipAdd = System.Net.Dns.GetHostEntry(host).AddressList[0]; //Listenするポート番号 int port = 2001; //TcpListenerオブジェクトを作成する System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(ipAdd, port); //Listenを開始する listener.Start(); Console.WriteLine($"Debug server started. port:{port}"); TaskContext tc = new TaskContext(); while (true) { Console.WriteLine($"Waiting client"); TcpClient client = listener.AcceptTcpClient(); Console.WriteLine($"Client is connected"); ClientTask ct = new ClientTask(); ct.Start(tc, client); } }
public static void updateServer() { while (true) { System.Net.Sockets.TcpClient chatConnection = chatServer.AcceptTcpClient(); Communicator newConnection = new Communicator(chatConnection, sendMessage); if (FileManager.checkBanList(newConnection.ipAddress)) { newConnection.writer.WriteLine("/%text%/"); newConnection.writer.WriteLine("You have been banned from this server.%/"); newConnection.writer.Flush(); newConnection.client.Close(); } else { if (newConnection.name != "Unnamed user") { List <string> tempString = new List <string>(); tempString.Add("/%text%/"); tempString.Add("\t" + newConnection.name + " has joined the chat.%/"); users.Add(newConnection); userChanger(); sendMessage(tempString); } } } }
/// <summary> /// Pojedyńczy wątek serwera. /// </summary> public void start() { NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=przemek;Database=template1;"); conn.Open(); QueryMaker qm = new QueryMaker(conn); serverSocket = new TcpListener(ip, port); TcpClient clientSocket; serverSocket.Start(); int counter = 0; while (true) { counter += 1; clientSocket = serverSocket.AcceptTcpClient(); HandleClient client = new HandleClient(clientSocket, Convert.ToString(counter), qm); Thread thread = new Thread(new ThreadStart(client.getMessage)); thread.Start(); } //conn.Close(); clientSocket.Close(); serverSocket.Stop(); }
public void Run() { Thread read = new Thread(Reader); read.IsBackground = true; TcpListener listen = new TcpListener(IPAddress.Parse("127.0.0.1"), 36345); listen.Start(); Thread.Sleep(100); read.Start(); var client = listen.AcceptTcpClient(); byte[] data = new byte[154600]; Stopwatch sw = new Stopwatch(); var stream = client.GetStream(); sw.Start(); for (int x = 0; x < Loop; x++) stream.Write(data, 0, data.Length); sw.Stop(); stream.Close(); Console.WriteLine("Write: " + ((Loop * data.Length) / sw.Elapsed.TotalSeconds / 1000000).ToString()); Thread.Sleep(1000); read.Join(); }
public void Listen() { TcpListener listener = new TcpListener(IPAddress.Any, Convert.ToInt32(ConfigurationManager.AppSettings["tcpPort"])); try { listener.Start(); int clientNr = 0; OnLogged("Waiting for a connection..."); while (continueProcess) { if (listener.Pending()) { TcpClient handler = listener.AcceptTcpClient(); if (handler != null) { OnLogged("Client #{0} accepted", ++clientNr); ClientHandler client = new ClientHandler(handler); client.Logged += Logged; connectionPool.Enqueue(client); } } Thread.Sleep(100); } } finally { listener.Stop(); } }
public void StopTcpListener () { var listener = new TcpListener (IPAddress.Loopback, 0); listener.Start (); listener.Stop (); Assert.Throws<InvalidOperationException> (() => listener.AcceptTcpClient ()); }
private void AcceptClients() { // format the prompting txtReceive.AppendText("==========\n"); client = server.AcceptTcpClient(); txtReceive.AppendText("==========\n"); }
public void Start() { // Create the listener var listener = new TcpListener(IPAddress.Any, Port); listener.Start(); try { while (true) { // Accept the Tcp connection from the clients var client = listener.AcceptTcpClient(); Trace.TraceInformation("Connection from {0}", client.Client.RemoteEndPoint); // The Handler should take care of the work from now var handler = new SslHandler(client, Certificate); var thread = new Thread(handler.Handle); handlers.Add(thread); thread.Start(); } } catch (ThreadAbortException tae) { handlers.ForEach(x => x.Abort()); } }
public void listen() { while (true) { portchanged = false; listener = new TcpListener(IPAddress.Any, Convert.ToInt32(settingsg.port)); listener.Start(); while (!portchanged) { TcpClient s = listener.AcceptTcpClient(); lastip = ((IPEndPoint)s.Client.RemoteEndPoint).Address.ToString(); //if (lastip.StartsWith("127") || lastip.StartsWith("192.168")) { hpr p = new hpr(s, this); new Thread(new ThreadStart(p.process)).Start(); } //else { //s.Close(); //ff.append(String.Format("{1}- Rejected external client {0}", lastip, DateTime.Now)); } } listener.Stop(); } }
private ServerCore() { LoadConfig(); RegisterCommanders(); try { sqlConnecter = SqlConnector.Instance; } catch (Exception ex) { Console.WriteLine("Could not connect to Mysql: \"" + ex.Message + "\""); Console.WriteLine("Aborting. Press any key to exit"); Console.Read(); return; } idConnection = new Dictionary<UInt32, TcpClient>(); connectionWorker = new Dictionary<TcpClient, ClientWorker>(); connectionId = new Dictionary<TcpClient, UInt32>(); workers = new List<ClientWorker>(); TcpListener tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Parse(ip), port); tcpListener.Start(); while (true) { TcpClient connection = tcpListener.AcceptTcpClient(); Console.WriteLine("Someone connected"); ClientWorker worker = new ClientWorker(connection); lock (mutex) { connectionWorker.Add(connection, worker); workers.Add(worker); } } }
static void Main(string[] args) { bool done = false; //TcpListener listener = new TcpListener(portNum); //����VS2005 MSDN �˷����Ѿ���ʱ������ʹ�� // IPEndPoint�� �������ʶΪIP��ַ�Ͷ˿ں� TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, portNum)); listener.Start(); while (!done) { Console.Write("Waiting for connection..."); TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("Connection accepted."); NetworkStream ns = client.GetStream(); byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString()); try { ns.Write(byteTime, 0, byteTime.Length); ns.Close(); client.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } listener.Stop(); }
private void ListenForClients() { tcplistener = new TcpListener(IPAddress.Loopback, int.Parse(ConfigurationManager.AppSettings["port"])); tcplistener.Start(); try { while (true) { //blocks until a client has connected to the server TcpClient client = tcplistener.AcceptTcpClient(); // here was first an message that send hello client // /////////////////////////////////////////////////// //create a thread to handle communication //with connected client Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); clientThread.Start(client); } } catch (SocketException e) { if ((e.SocketErrorCode == SocketError.Interrupted)) { } } }
public void threadmain(object parameters) { ownerGUI.NetDebugConsole("Listen Thread Started!"); listener = new TcpListener(System.Net.IPAddress.Any, port); listener.Start(); while (true) { TcpClient client = listener.AcceptTcpClient(); ownerGUI.NetDebugConsole("Listen Loop"); //NetworkStream s = client.GetStream(); while (true) { byte[] inBuffer = new byte[16]; client.Client.Receive(inBuffer); string rec = ""; for(int i = 0; i < inBuffer.Length; i++) { rec += (char)inBuffer[i]; } ownerGUI.NetDebugConsole("REC:" + rec); //owner //owner.textBoxLog.Text += rec; } } }
public void waitForClients() { // create network Socket (winsok) //TODO : basculer Socket dans socketManager prévu à cet effet. //TODO : enlever valeurs par défaut et passer paramètres depuis main IPAddress ipaddress = new IPAddress(new byte[] { 127, 0, 0, 1 }); TcpListener tcpl = new TcpListener(ipaddress, 2106); tcpl.Start(); while (_serverRunning) { Display.displayMessage("Thread tourne."); TcpClient tcpC = tcpl.AcceptTcpClient(); if (tcpC.Connected) { Display.displayMessage("Client connecté !! "); Display.displayMessage("Address : " + tcpC.Client.RemoteEndPoint.ToString()); // Create Thread for its process. Thread playerHandler = new Thread(new ParameterizedThreadStart(handleIncomingClient)); playerHandler.Start(tcpC); } } Thread.Sleep(100); }
public void Start() { try { listener = new TcpListener(IPAddress.Parse(ServerIP), ServerPort); listener.Start(); while (running) { TcpClient client = null; try { client = listener.AcceptTcpClient(); Console.WriteLine("AudioServer Accept"); new Thread(new AudioSender(client.GetStream()).Start).Start(); } catch (Exception) { if (client != null) client.Close(); } } Console.WriteLine("AudioServer Done"); } catch (Exception) { } }
Program() { IPAddress ip = Info.GetIp(); TcpListener listener = new TcpListener(ip,Info.Port); storage = new DataStorage(); listener.Start(); int counter = 0; Console.WriteLine("Server started: {0}",DateTime.Now); Console.WriteLine("Server ip: {0}", ip); Console.WriteLine("Server port: {0}",Info.Port); while (true) { TcpClient newClient = listener.AcceptTcpClient(); if (!IsMonitor(newClient)) { counter++; Console.WriteLine("is client"); Client client = new Client(newClient, this, counter, storage); clients.Add(client); } else if (_monitor != null) { if (!_monitor.TcpClient.Connected) { _monitor = new Monitor(newClient,this,clients, storage); } } else { _monitor = new Monitor(newClient,this,clients, storage); } } }
static void Main(string[] args) { TcpListener listener = new TcpListener(IPAddress.Any, 1337); listener.Start(); Random rand = new Random(); string[] types = new string[] { "Hjarta", "Spaði", "Tígull", "Lauf" }; while (true) { try { TcpClient client = listener.AcceptTcpClient(); StreamWriter sw = new StreamWriter(client.GetStream()); while (true) { Thread.Sleep(1000); string s = types[rand.Next(0, types.Length)] + " "; int n = rand.Next(1, 14); if (n == 1) s += "Ás"; else if (n <= 10) s += n; else if (n == 11) s += "Gosi"; else if (n == 12) s += "Drottning"; else if (n == 13) s += "Kongur"; sw.WriteLine(s); sw.Flush(); } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } } }
private void Listen() { while (true) { System.Net.Sockets.TcpClient tmp = tcp.AcceptTcpClient(); clients.Add(tmp); } }
public void Open() { Console.WriteLine("Waiting for first connection to " + listener.Server.LocalEndPoint); Client = listener.AcceptTcpClient(); // any connection from here on in will auto connect listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener); }
static void Main(string[] args) { // System.Net.IPAddress localAdd = System.Net.IPAddress.Parse("10.0.1.2"); System.Net.IPAddress localAdd = System.Net.IPAddress.Parse("127.0.0.1"); System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(localAdd, portNo); listener.Start(); while (true) { ChatClient user = new ChatClient(listener.AcceptTcpClient()); } }
private void StartReceive() { while (true) { _tcpClient = _tcpListener.AcceptTcpClient(); byte[] bytes = new byte[1024]; NetworkStream stream = _tcpClient.GetStream(); stream.Read(bytes, 0, bytes.Length); Receive(bytes); } }
private void ListenRequests() { // Create listener on localhost port 4002, the server will listen on that port. Int32 port = 4002; //Ignore IP Address System.Net.IPAddress localAddr = current_IP; try { tcpListener = new System.Net.Sockets.TcpListener(localAddr, port); tcpListener.Start(); Debug.Log("Server is listening"); Byte[] bytes = new Byte[1024]; /* REFORMAT THIS */ while (true) { using (connectedTcpClient = tcpListener.AcceptTcpClient()) { // Get a stream object for reading using (stream = connectedTcpClient.GetStream()) { int length; // Read incoming stream of data, if there is data. while ((length = stream.Read(bytes, 0, bytes.Length)) != 0) { //Debugger Debug.Log("Listening for incoming requests"); //Read the data that was sent. var data = new byte[length]; Array.Copy(bytes, 0, data, 0, length); // Convert byte array to string message. string clientMessage = Encoding.ASCII.GetString(data); Debug.Log("clientMessage: " + clientMessage); //Write an answer to the client: it's the current instruction. string response = currentInstruction; sendClient(response); //var e = "hllo"; //e.ToString; } } } } } catch (System.Net.Sockets.SocketException socketException) { Debug.Log("SocketException " + socketException.ToString()); } }
public static void Main() { IPAddress myIP = IPAddress.Parse("127.0.0.1"); IPEndPoint myIpEndPoint = new IPEndPoint(myIP, 8888); System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(myIpEndPoint); listener.Start(); Console.WriteLine( "Listenを開始しました({0}:{1})。", ((IPEndPoint)listener.LocalEndpoint).Address, ((IPEndPoint)listener.LocalEndpoint).Port ); System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); Console.WriteLine( "クライアント({0}:{1})と接続しました。", ((IPEndPoint)client.Client.RemoteEndPoint).Address, ((IPEndPoint)client.Client.RemoteEndPoint).Port ); System.Net.Sockets.NetworkStream ns = client.GetStream(); System.Text.Encoding enc = System.Text.Encoding.UTF8; Queue <string> messages = new Queue <string>(510); while (ns.CanRead) { int resSize = 0; byte[] resBytes = new byte[2048]; System.IO.MemoryStream ms = new System.IO.MemoryStream(); do { resSize = ns.Read(resBytes, 0, resBytes.Length); ms.Write(resBytes, 0, resSize); } while (ns.DataAvailable); string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); resMsg = resMsg.TrimEnd('\n'); ms.Close(); messages.Enqueue(resMsg); if (messages.Count > 500) { messages.Dequeue(); } System.IO.StreamWriter sw = new System.IO.StreamWriter(@"FC2.log", false, System.Text.Encoding.GetEncoding("utf-8")); sw.Write(string.Join("\n", messages.ToArray())); sw.Close(); Console.WriteLine("{0}", resMsg); } }
public void clientListener() { // Create threads for robot controller and phones this.clientRobotControllerThread = new System.Threading.Thread(new System.Threading.ThreadStart(receiveFromRobotController)); //this.clientPhoneThread = new System.Threading.Thread(new System.Threading.ThreadStart(sendToPhone)); phoneClientCounter = 0; while (this.shutDown_clientListener == false) { Debug.Write("Listening for new clients" + "\n"); // Listening for new client TcpClient tcpClientTemp = tcpserver.AcceptTcpClient(); // Receive name of client and add client to dictonary // If name already exist create another one string clientName = receiveClientName(tcpClientTemp); Debug.Write("clientName: " + clientName + "\n"); if (clientName.Equals("Phone")) { clientName = clientName + phoneClientCounter.ToString(); Debug.Write("clientName modified: " + clientName + "\n"); clientList.Add(clientName, tcpClientTemp); phoneClientCounter += 1; } if (clientName.Equals("RobotController")) { clientList.Add(clientName, tcpClientTemp); } // Send answer to client that clientname is received Debug.Write("Call sendToPhone" + "\n"); sendToClient(":p:1;", tcpClientTemp); // Start new thread for robot controller if (clientList.ContainsKey("RobotController") && !(this.clientRobotControllerThread.ThreadState == System.Threading.ThreadState.Running)) { this.clientRobotControllerThread.Start(); Debug.Write("clientRobotControllerThread started" + "\n"); } // Start new thread for phones //if (clientList.ContainsKey("Phone") && !(this.clientPhoneThread.ThreadState == System.Threading.ThreadState.Running)) //{ //Debug.Write("clientPhoneThread started" + "\n"); //this.clientPhoneThread.Start(); // } } if (this.statusChangedEvent != null) { this.statusChangedEvent(this.communicationName + ": New client connected. Start receiving"); } }
private void handleIncomingPeers() { Client peer; while (listener.Pending()) { peer = new Client(listener.AcceptTcpClient()); Console.WriteLine("incomming client"); string name = peer.IPAddress + ":" + peer.Port; // figure out name addPeer(name, peer); // add them to our peers } }
/// <summary> /// This method takes care of network communication: wait for incoming connection and spawns NetworkWorkers /// </summary> private void Run() { _listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, int.Parse(Settings.Default.HOST_SERVER_PORT)); _listener.Start(); while (true) { TcpClient c = _listener.AcceptTcpClient(); NetworkWorker w = new NetworkWorker(c); _workers.Add(w); ((IWorker)w).Start(); } }
public void Start() { try { _serverListener.Start(); var bytes = new byte[256]; while (true) { WriteLine("Waiting for a connection to port " + _port + "..."); TcpClient client; try { client = _serverListener.AcceptTcpClient(); } catch (Exception e) { WriteLine("Connection error " + e); break; } WriteLine("Connected !"); var stream = client.GetStream(); int i; while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { var data = Encoding.ASCII.GetString(bytes, 0, i); WriteLine("Received: {0}", data); data = data.ToUpper(); var msgBytes = Encoding.ASCII.GetBytes(data); stream.Write(msgBytes, 0, msgBytes.Length); WriteLine("Sent: {0}", data); } client.Close(); } } catch (SocketException e) { WriteLine("SocketException : " + e); } finally { _serverListener.Stop(); } Read(); }
public void Start() { listener = new System.Net.Sockets.TcpListener(port); listener.Start(); while (is_active) { System.Net.Sockets.TcpClient s = listener.AcceptTcpClient(); Processor processor = new Processor(s, this); Thread thread = new Thread(new ThreadStart(processor.process)); thread.Start(); Thread.Sleep(1); } }
private void Listen() { try { bool done = false; TcpListen = new System.Net.Sockets.TcpListener(6811); Debug.Log(TcpListen); TcpListen.Start(); System.Net.Sockets.TcpClient client = TcpListen.AcceptTcpClient(); Debug.Log(client); if (client != null) { m_NetworkStream = client.GetStream(); System.Net.Sockets.NetworkStream ns = m_NetworkStream; //listen Receive StartReceiveData(); while (!done) { if (ns != null) { continue; //pause one test/**/ Debug.Log(ns); //CWritePacket packet = new CWritePacket((int)D2CMessage.EBuilding_Update); //packet.WriteInt(345); //packet.WriteString("keyinishihuaihaizi"); //packet.WriteShort(15); //packet.WriteByte(10); try { //ns.Write( packet.GetPacketByte(), 0, packet.GetPacketLen() ); //ns.Close(); //client.Close(); } catch (System.Exception ex) { Debug.Log("listen error!" + ex.Message); } } } } } catch (System.Exception ex) { Debug.Log("listen error111!" + ex.Message); } }
public TalkServ() { server = new System.Net.Sockets.TcpListener(85); Console.WriteLine("Started News Server.\nNews are:\n" + NEWS); while (true) { server.Start(); if (server.Pending()) { N.Sockets.TcpClient connection = server.AcceptTcpClient(); Console.WriteLine("Connecting client!"); BackForth BF = new BackForth(connection); } } }
private static void Main() { var localhost = IPAddress.Parse(DefaultIpAAddress); var listener = new TcpIpListener(localhost, DefaultListeningPort); listener.Start(); while (true) { Console.WriteLine("Waiting for connection"); var client = listener.AcceptTcpClient(); // Объект AcceptTcpClient ждет соединения с клиентом var thread = new Thread(HandleClientThread); // Запустить новый поток выполнения для обработки этого соединения, thread.Start(client); // чтобы иметь возможность вернуться к ожиданию очередного соединения } }
private void StartListening() { System.Net.Sockets.TcpListener server = null; try { server = new System.Net.Sockets.TcpListener(IPAddress.Parse(myIPAddress), Port); server.Start(); TcpClient lastClient = null; while (true) { AllDone.Reset(); if (Logger.Enabled) { Logger.Log("Ready for connection..."); } var client = server.AcceptTcpClient(); if (client == lastClient) { Console.WriteLine("last client"); } lastClient = client; if (Logger.Enabled) { Logger.Log("Connected!"); } Thread.Sleep(100); new Thread(() => HandleMessage(client)).Start(); } } catch (SocketException e) { if (Logger.Enabled) { Logger.Log(string.Format("SocketException: {0}", e)); } } finally { //Stop listening for new clients server.Stop(); } }
public void StartMessage() { var ipaddr = IPAddress.Parse(ipaddress); try { System.Net.Sockets.TcpListener serverListener = new System.Net.Sockets.TcpListener(ipaddr, 4444); serverListener.Start(); FTPServer.Logger.Text += "머신서버 가동>>>>\n"; for (; ;) { var machineSocket = serverListener.AcceptTcpClient();//접속된 클라이언트 반환 string machineName = null; if (machineSocket.Connected) { var ns = machineSocket.GetStream(); Byte[] byteFrom = new Byte[machineSocket.SendBufferSize]; ns.Read(byteFrom, 0, machineSocket.SendBufferSize); machineName = Encoding.UTF8.GetString(byteFrom); int index = machineName.IndexOf("\0"); machineName = machineName.Remove(index, machineName.Length - index); FTPServer.Logger.Text += "기계접속을 감지했습니다\n"; if (!machineTable.Contains(machineName)) { FTPServer.Logger.Text += "\n" + machineName + "\n"; //참여자 목록(clientList)을 클라이언트 접속한 클라이언트에 접속 MachineClientSocket client = new MachineClientSocket(machineSocket, machineName, machineTable); machineTable.Add(machineName, client);//머신 관리 } else { Unicast("해당 기계는 이미 등록되어있습니다", machineSocket); } } } } catch (Exception) { throw; }//서버가 대기하기 시작함 }
void ServerWaiting() { System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString); listener = new System.Net.Sockets.TcpListener(ipAdd, port); listener.Start(); HostIP_Port = ((IPEndPoint)listener.LocalEndpoint).Address.ToString() + " : " + ((IPEndPoint)listener.LocalEndpoint).Port.ToString(); client = listener.AcceptTcpClient(); ClientIP_Port = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString() + " : " + ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port.ToString(); DispIPInfo(); DEBUG_STR = "Client: Connect\n" + ClientIP_Port; DispIPInfo(); ServerThread = new Thread(ServerReadWrite); ServerThread.Priority = ThreadPriority.Lowest; ServerThread.Start(); }
private void Run() { TcpListener _listener = new System.Net.Sockets.TcpListener(IPAddress.Any, 5500); //_listener.ExclusiveAddressUse = false; _listener.Start(); while (this._isRunning) { var client = _listener.AcceptTcpClient(); if (OnConnection != null) { var args = new ListenerEventArgs(); args.Client = client; OnConnection(this, args); } } }