/// <summary> /// This method will constantly run as a thread. It currently sends a multicast to the network every second, informing /// computers on the network that it is there. When a client sees this, it will send a message to the server and the client /// will be added to the clients list. /// </summary> public static void AddClients() { clients = new List<ClientThread>(); TcpListener serverSocket = new TcpListener(IPAddress.Any, 8888); serverSocket.Start(); while (true) { TcpClient tempClientSocket = new TcpClient(); tempClientSocket.ReceiveTimeout = 300; SendMulticast(); //Check and see if a computer is trying to connect. //If not, then sleep, and resend multicast in a second if (serverSocket.Pending()) { tempClientSocket = serverSocket.AcceptTcpClient(); ClientThread c = new ClientThread(tempClientSocket,null); clients.Add(c); Console.WriteLine("Connected to " + c.GetClientIP() + " :: "+c.GetPort()); } else { Thread.Sleep(1000); //Sleep for a second, before sending the next multicast. } } }
public ChatServer() { // create nickName & nickNameByConnect variables nickName = new Hashtable(100); nickNameByConnect = new Hashtable(100); // initialise chatServer with at the local IP address host on port 4296 chatServer = new TcpListener(host, 4296); // check to see that the server is running // visual indication server is running Console.WriteLine("Server Running"); //keep running while (true) { // start the server chatServer.Start(); // if there are connections pending if (chatServer.Pending()) { // accept the connection Chat.Sockets.TcpClient chatConnection = chatServer.AcceptTcpClient(); // display message to client Console.WriteLine("You are now connected"); // create a new DoCommunicate object DoCommunicate comm = new DoCommunicate(chatConnection); } } }
public void NoChannelForkGroup() { using (ShortcutTestClass shortcutTestClass = ParallelizationFactory.GetParallelized<ShortcutTestClass>()) { TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000); tcpListener.Start(); shortcutTestClass.NoChannelForkGroup("Test"); int i = 0; while (!tcpListener.Pending()) { Thread.Sleep(100); if (i++ > 20) { tcpListener.Stop(); throw new TimeoutException(); } } TcpClient tcpClient = tcpListener.AcceptTcpClient(); Expect(new StreamReader(tcpClient.GetStream()).ReadToEnd(), EqualTo("Test")); tcpClient.Close(); tcpListener.Stop(); } }
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 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 StartThread() { Print("Server started"); var listner=new TcpListener(IPAddress.Any, port); listner.Start(); CvarcClient cvarcClient = null; while(true) { while (!listner.Pending()) { if (exitRequest) { if (cvarcClient != null) cvarcClient.Close(); listner.Stop(); return; } Thread.Sleep(1); } var client = listner.AcceptTcpClient(); Print("Client accepted"); if (cvarcClient != null) cvarcClient.Close(); // этот метод должен внутри CvarcClient устанавливать флаг, при котором цикл внутри Read заканчивается исключением cvarcClient = new CvarcClient(client); if (ClientConnected != null) ClientConnected(cvarcClient); } }
static void Main(string[] args) { var settings = ConfigurationManager.AppSettings; var port = settings["COM_PORT"]; var speed = Convert.ToInt32(settings["COM_SPEED"]); var tcpPort = Convert.ToInt32(settings["TCP_PORT"]); serial = new SerialManager(port, speed); Console.WriteLine("UART: " + port + " - " + speed); server = new HardwareTcpServer(tcpPort); server.OnServerState += server_OnServerState; server.OnClientState += server_OnClientState; server.OnData += server_OnData; serial.OnReceive += serial_OnReceive; serial.OnStateChange += serial_OnStateChange; serial.Connect(); // bridge = new HttpToUartBridge(6200); TcpListener listener = new TcpListener(IPAddress.Parse("188.127.233.35"), tcpPort); listener.Start(); Console.WriteLine("TCP: " + tcpPort); while (Thread.CurrentThread.ThreadState == ThreadState.Running) { Console.WriteLine("Listening " + tcpPort); while (!listener.Pending()) { Thread.Sleep(300); } server.AcceptTcpClient(listener.AcceptSocket()); } Console.WriteLine("Stopped"); listener.Stop(); server.Close(); serial.Close(); }
private void Listen() { TcpListener tcpListener = new TcpListener(IPAddress.Any, ListenPort); tcpListener.Start(); TcpClient client = null; try { while (!CloseClass) { if (!tcpListener.Pending()) { Thread.Yield(); } else { client = tcpListener.AcceptTcpClient(); ThreadPool.QueueUserWorkItem(x => returnMethod(client)); } } } finally { if (client != null) { client.Close(); } tcpListener.Stop(); } }
public void run() { Debug.Log("ACCEPTOR THREAD: Starting Tcp Listener"); try { tcpListener = new TcpListener(IPAddress.Any, 4444); tcpListener.Start (); //new Thread (new ThreadStart (DiscoveryThread.Instance.run)).Start(); Debug.Log("ACCEPTOR THREAD: Waiting for clients..."); while (_isRunning) { while (!tcpListener.Pending()) { Thread.Sleep (1000); } Debug.Log("ACCEPTOR THREAD: Client accepted!"); ConnectionThread newconnection = new ConnectionThread(tcpListener); runningConnections.Add(newconnection); new Thread (new ThreadStart (newconnection.HandleConnection)).Start(); Thread.Sleep(100); } } catch (Exception e) { Debug.LogError (e.ToString()); } Debug.Log("ACCEPTOR THREAD: TCP Requesting Stop from " + runningConnections.Count + " open connections"); foreach (ConnectionThread connection in runningConnections) { connection.RequestStop(); } Debug.Log("ACCEPTOR THREAD: Ending..."); }
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 { } }
public static void ReceiveTCP(int portN) { TcpListener Listener = null; try { Listener = new TcpListener(IPAddress.Any, portN); Listener.Start(); } catch (Exception ex) { Console.WriteLine(ex.Message); } int BufferSize = 4096; byte[] RecData = new byte[BufferSize]; int RecBytes; for (; ; ) { TcpClient client = null; NetworkStream netstream = null; //Status = string.Empty; try { string message = "Accept the Incoming File "; string caption = "Incoming Connection"; //MessageBoxButtons buttons = MessageBoxButtons.YesNo; //DialogResult result; if (Listener.Pending()) { client = Listener.AcceptTcpClient(); netstream = client.GetStream(); //Status = "Connected to a client\n"; //result = MessageBox.Show(message, caption, buttons); Console.WriteLine("Connected to a sender"); string dirPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string SaveFileName = dirPath+"\\"+string.Format("RecvdFile-{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now); if (SaveFileName != string.Empty) { int totalrecbytes = 0; FileStream Fs = new FileStream(SaveFileName, FileMode.OpenOrCreate, FileAccess.Write); while ((RecBytes = netstream.Read(RecData, 0, RecData.Length)) > 0) { Fs.Write(RecData, 0, RecBytes); totalrecbytes += RecBytes; } Fs.Close(); } netstream.Close(); client.Close(); } } catch (Exception ex) { Console.WriteLine(ex.Message); //netstream.Close(); } } }
/// <summary> /// Monitor pentru starea firului de execuţie de rezolvare a cererilor. /// </summary> //private ManualResetEvent tcpClientConnected; /// <param name="iTransformer">Transformatorul de cereri în răspuns</param> /// <param name="port">Portul pe care se ascultă</param> public Replyer(ITransformer iTransformer, int port) { this.iTransformer = iTransformer; TcpListener tcpl = new TcpListener(IPAddress.Any, port); tcpl.Start(); while (true) { try { while (!tcpl.Pending()) { Thread.Sleep(1000); } TcpClient client = tcpl.AcceptTcpClient(); ThreadPool.QueueUserWorkItem(receiveTransformAndSendFeedback, client); } catch (ThreadAbortException) { tcpl.Stop(); return; } } }
public static void Start(int port) { TcpListener listener = new TcpListener (IPAddress.Loopback, port); listener.Start (); while (run) { while (!listener.Pending() && run) { Thread.Sleep (200); } if (!run) break; Socket newSocket = listener.AcceptSocket (); Thread thread = new Thread (new ParameterizedThreadStart (Handshaker)); int id = 0; lock (serviceThreads) { id = serviceThreads.Count > 0 ? serviceThreads.Keys.Max () + 1 : 0; serviceThreads.Add (id, thread); } thread.Start (new object[] { id, newSocket }); } }
public void Listen(int port) { TcpListener serverSocket = new TcpListener(IPAddress.Parse("127.0.0.1"), port); TcpClient clientSocket = default(TcpClient); serverSocket.Start(); Console.WriteLine(" >> Server Started"); try { while (true) { if (serverSocket.Pending()) { clientSocket = serverSocket.AcceptTcpClient(); ThreadPool.QueueUserWorkItem(o => ProcessRequest(clientSocket)); } else { Thread.Sleep(100); } } } catch (ThreadAbortException) { Console.WriteLine(" >> Server Ended"); t = null; } }
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 MassiveInvoke() { using (ChordTestClass chordTestClass = ParallelizationFactory.GetParallelized<ChordTestClass>()) { List<TcpListener> tcpListeners = new List<TcpListener>(); for (int i = 0; i < 500; i++) { TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000 + i); tcpListeners.Add(tcpListener); tcpListener.Start(); chordTestClass.TestMethod4(string.Format("V{0}", i)); chordTestClass.TestMethod5(i); } List<string> results = new List<string>(); foreach (TcpListener tcpListener in tcpListeners) { int i = 0; var timeout = 10; while (!tcpListener.Pending()) { Thread.Sleep(100); if (++i > timeout) { tcpListener.Stop(); throw new TimeoutException(); } } TcpClient tcpClient = tcpListener.AcceptTcpClient(); results.Add(new BinaryReader(tcpClient.GetStream()).ReadString()); tcpClient.Close(); tcpListener.Stop(); } Debug.Print(string.Format("Received {0} results.", results.Count)); List<string> results1 = new List<string>(); List<string> results2 = new List<string>(); foreach(string value in results) { string[] values = value.Split(','); results1.Add(values[0]); results2.Add(values[1]); } for (int i = 0; i < 500; i++) { Expect(results1.Contains(string.Format("V{0}", i)), string.Format("Missing value1: {0}", i)); Expect(results2.Contains(string.Format("{0}", 23000 + i)), string.Format("Missing value2: {0}", i)); } } }
public void startServer() { run = true; IPHostEntry host; string localIP = ""; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); } } TcpListener serverSocket = new TcpListener(IPAddress.Parse(localIP), 10000); TcpClient clientSocket = default(TcpClient); clientList = new List<ClientHandler>(); int counter = 0; serverSocket.Start(); Console.WriteLine(" >> " + "Server Started @ "+localIP); counter = 0; while (run) { if (!serverSocket.Pending()) { Thread.Sleep(500); continue; } else { counter += 1; clientSocket = serverSocket.AcceptTcpClient(); Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " has connected"); ClientHandler client = new ClientHandler(); clientList.Add(client); client.startClient(clientSocket, Convert.ToString(counter)); client.newMessageToSend = messageHandler; startClientThread(); } } //kill the client threads if (!run) { foreach (ClientHandler element in clientList) { if(element != null && element.running == true) { element.running = false; } } } serverSocket.Stop(); Console.WriteLine(" >> " + "exit"); Console.ReadLine(); }
static void Main(string[] args) { ServerConfig.ParseConfig(args); Logger.InitWithName(ServerConfig.Name); Thread.CurrentThread.Name = "SERVER"; var slave = new TcpListener(ServerConfig.ListenPort); try { try { slave.Start(10); } catch { throw new Exception(@"Невозможно открыть сокет №" + ServerConfig.ListenPort.ToString()); } while (true) { TcpClient connect = null; if (slave.Pending()) { try { connect = slave.AcceptTcpClient(); } catch { } } if (connect == null) {Thread.Sleep(500); continue;} if (connect.Connected) { Terminal terminal = new Terminal(connect); Thread thread = new Thread(Terminal.DoWork); thread.Start(terminal); } Thread.Sleep(0); } } catch (OutOfMemoryException e) { Logger.WriteMessage(Logger.EventID.ServiceCrash, @"ПЕРЕПОЛНЕНИЕ ВИРТУАЛЬНОЙ ПАМЯТИ: " + e.ToString()); } catch (Exception ex) { Logger.WriteMessage(Logger.EventID.ServiceCrash, ex.ToString()); } finally { slave.Stop(); Logger.Close(); } }
static void Main(string[] args) { try { // create TCP listener TcpListener tcpListen = new TcpListener(IPAddress.Any, 11000); tcpListen.Start(); // check for a connection every two seconds while (!tcpListen.Pending()) { Console.WriteLine("Still listening. Will try again in 2 seconds."); Thread.Sleep(2000); } using (TcpClient tcp = tcpListen.AcceptTcpClient()) { NetworkStream netStream = tcp.GetStream(); // create RijndaelManaged instance and encrypt RijndaelManaged rm = new RijndaelManaged(); // set key and IV //byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, // 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16}; //byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, // 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16}; // alternatively, generate key and IV from a shared secret (password) // password and salt are inputs to key generation, which makes dictionary // attacks more difficult than if the input was just the password string password = "******"; byte[] salt = Encoding.ASCII.GetBytes("This is my salt"); Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt); byte[] Key = key.GetBytes(rm.KeySize / 8); byte[] IV = key.GetBytes(rm.BlockSize / 8); CryptoStream cryptStream = new CryptoStream(netStream, rm.CreateDecryptor(Key, IV), CryptoStreamMode.Read); using (StreamReader sReader = new StreamReader(cryptStream)) { Console.WriteLine("The decrypted message is: {0}", sReader.ReadToEnd()); sReader.Close(); } tcp.Close(); Console.ReadKey(); } } catch { Console.WriteLine("The listener failed"); } }
private void ListenForClientsProc(CancellationTokenSource cts) { IsListeningChanged?.Invoke(true); try { while (!cts.Token.IsCancellationRequested && (_server != null)) { System.Threading.Thread.Sleep(1); if (IsListening && !_server.Pending()) { continue; } TcpClient client = null; try { client = _server.AcceptTcpClientAsync().Result; } catch (NullReferenceException) { break; } catch (ObjectDisposedException) { break; } catch (SocketException e) { if (e.SocketErrorCode != SocketError.Interrupted) //the server was stopped { Log.e("SocketException: Socket Error Code {0}: {1}\n{2}", e.SocketErrorCode, Enum.GetName(typeof(System.Net.Sockets.SocketError), e.SocketErrorCode), e.ToString()); } break; } catch (Exception e) { Log.e(e); break; } OnCreateClientHandler(client); } } catch (Exception e) { Log.e(e); } finally { IsListening = false; IsListeningChanged?.Invoke(IsListening); } }
public void receiveConnection(TcpListener listener) { while (true) { if (listener.Pending()) { tcpSocket = listener.AcceptSocket(); return; } } }
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 } }
protected void Listener(object obj) { _listener = new TcpListener(IPAddress.Parse((string)Config.Configuration["IPAddress"]), (int)Config.Configuration["Port"]); _listener.Start(100); while (true) { if (_listener.Pending()) _listener.BeginAcceptTcpClient(new AsyncCallback(AsyncResult_newcon), (object)"New Connection"); else Thread.Sleep(1); } }
public Task<KeyValuePair<string, string>?> Listen(IPAddress ip, int port, int timeout = 0, bool waitForValid = false) { return Task<KeyValuePair<string, string>?>.Factory.StartNew(() => { var end = DateTime.Now.AddMilliseconds(timeout); TcpListener listener = null; try { listener = new TcpListener(ip, port); listener.ExclusiveAddressUse = false; listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); listener.Server.ReceiveTimeout = timeout; listener.Start(); do { if (listener.Pending()) { using (var client = listener.AcceptTcpClient()) { using (var stream = new StreamReader(client.GetStream())) { var data = new byte[4096]; try { var message = stream.ReadLine(); var split = message.Split(':'); if (split.Length == 2) { return new KeyValuePair<string, string>(split[0], split[1]); } } catch { } } } } else if (DateTime.Now >= end) return null; } while (waitForValid); } finally { if (listener != null) { listener.Stop(); if (listener.Server != null) listener.Server.Dispose(); } } return null; }); }
public void StartReceive() { //创建一个网络端点 IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port); //创建网络监听 lisner = new TcpListener(ipep); lisner.Start(); while (true) { ////确认连接 if (!lisner.Pending()) { Thread.Sleep(1000); continue; } //MessageBox.Show("1"); Socket client = lisner.AcceptSocket(); //获得客户端节点对象 IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; //获得[文件名] string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)); //获得[包的大小] string bagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)); //获得[包的总数量] int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client))); //获得[最后一个包的大小] string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)); //创建一个新文件 string fileFullName = "d:\\" + SendFileName; FileStream MyFileStream = new FileStream(fileFullName, FileMode.Create, FileAccess.Write, FileShare.Read); //已发送包的个数 int SendedCount = 0; while (true) { byte[] data = TransferFiles.ReceiveVarData(client); if (data.Length == 0) { break; } else { SendedCount++; //将接收到的数据包写入到文件流对象 MyFileStream.Write(data, 0, data.Length); } } //关闭文件流 MyFileStream.Close(); //关闭套接字 client.Close(); } }
public TalkServ() { handles = new Hashtable(100); handleByConnect = new Hashtable(100); server = new System.Net.Sockets.TcpListener(4296); while(true) { server.Start(); if(server.Pending()) { N.Sockets.TcpClient connection = server.AcceptTcpClient(); Console.WriteLine("Connection made"); BackForth BF = new BackForth(connection); } } }
protected void функция_потока() { TcpListener listner = null; try { listner = new TcpListener(5595); listner.Start(); byte[] data = new byte[512]; string str; PrintMsg("Wait client"); while (true) { if (listner.Pending()) { str = null; TcpClient client = listner.AcceptTcpClient(); PrintMsg("Connected"); NetworkStream stream = client.GetStream(); int i; byte[] msgbyte = new byte[512]; while ((i = stream.Read(data, 0, data.Length)) != 0) { for (int j = 0; j < i; j++) if (data[j] == 1) str += 1; else str += 0; } PrintMsg("Полученное закодированное сообщение в двоичном формате :\n" + str); byte[] vec = new byte[str.Length]; for (int j = 0; j < str.Length; j++) if (str[j] == '1') vec[j] = 1; else vec[j] = 0; Hamming_Decoder hd = new Hamming_Decoder(vec); hd.добавитьОшибку(); byte[] vec2 = hd.вернутьДанныеБезДекодирования(); PrintMsg("Полученное закодированное сообщение в двоичном формате с ошибкой:\n" + вСтроку(vec2)); vec2 = hd.декодировать(0); PrintMsg("Разкодированное сообщение с ошибкой:\n" + конвертировать(vec2)); //PrintMsg(); vec = hd.декодировать(1); PrintMsg("Разкодированное сообщение с исправленной ошибкой:\n" + конвертировать(vec)); client.Close(); PrintMsg("Wait client"); } } } catch (SocketException e) { PrintMsg(e.Message); } finally { listner.Stop(); } }
protected override TcpClient connectSpecific() { TcpListener host = new TcpListener(System.Net.IPAddress.Any, Global.WIFI_PORT); host.Start(); while (!host.Pending() && isAlive) System.Threading.Thread.Sleep(200); TcpClient client = null; if(isAlive) client = host.AcceptTcpClient(); host.Stop(); return client; }
public void MassiveInvoke() { using (ForkTestClass forkTestClass = ParallelizationFactory.GetParallelized<ForkTestClass>()) { List<TcpListener> tcpListeners = new List<TcpListener>(); for (int i = 0; i < 500; i++) { TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000 + i); tcpListeners.Add(tcpListener); tcpListener.Start(); forkTestClass.MassiveTest(i.ToString()); } List<int> results = new List<int>(); foreach (TcpListener tcpListener in tcpListeners) { int i = 0; var timeout = 10; while (!tcpListener.Pending()) { Thread.Sleep(100); if (++i > timeout) { tcpListener.Stop(); throw new TimeoutException(); } } if(i > timeout) continue; TcpClient tcpClient = tcpListener.AcceptTcpClient(); results.Add(new BinaryReader(tcpClient.GetStream()).ReadInt32()); tcpClient.Close(); tcpListener.Stop(); } Debug.Print(string.Format("Received {0} results.", results.Count)); for (int i = 0; i < 500; i++) { Expect(results.Contains(i), string.Format("Missing value: {0}", i)); } } }
public void TcpListener () { var port = NetworkHelpers.FindFreePort (); // listen with a new listener (IPv4 is the default) TcpListener inListener = new TcpListener (port); inListener.Start(); // connect to it from a new socket IPHostEntry hostent = Dns.GetHostByAddress (IPAddress.Loopback); Socket outSock = null; foreach (IPAddress address in hostent.AddressList) { if (address.AddressFamily == AddressFamily.InterNetwork) { /// Only keep IPv4 addresses, our Server is in IPv4 only mode. outSock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.IP); IPEndPoint remote = new IPEndPoint (address, port); outSock.Connect (remote); break; } } // make sure the connection arrives Assert.IsTrue (inListener.Pending ()); Socket inSock = inListener.AcceptSocket (); // now send some data and see if it comes out the other end const int len = 1024; byte[] outBuf = new Byte [len]; for (int i=0; i<len; i++) outBuf [i] = (byte) (i % 256); outSock.Send (outBuf, 0, len, 0); byte[] inBuf = new Byte[len]; int ret = inSock.Receive (inBuf, 0, len, 0); // let's see if it arrived OK Assert.IsTrue (ret != 0); for (int i=0; i<len; i++) Assert.IsTrue (inBuf[i] == outBuf [i]); // tidy up after ourselves inSock.Close (); inListener.Stop (); }
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); } } }
public Server() { listener = new TcpListener(IPAddress.Loopback, 9090); listener.Start(); Console.WriteLine("Waiting for clients..."); while (true) { while (!listener.Pending()) { Thread.Sleep(1000); } ConnectionThread newConnection = new ConnectionThread(); newConnection.threadListener = this.listener; ThreadPool.QueueUserWorkItem(new WaitCallback(newConnection.HandleConnection)); } }
public appserver(string path) { TcpListener mylist = new TcpListener(IPAddress.Loopback, 3299); mylist.Start(); while (SocialVars.Running) { if (mylist.Pending()) { Stream clientStream = mylist.AcceptTcpClient().GetStream(); webclient myclient = new webclient(clientStream, path); } System.Threading.Thread.Sleep(20); } mylist.Stop(); }
static void Main(string[] args) { MessageTypes.Init(); tcpListener = new TcpListener(IPAddress.Any, 2594); tcpListener.Start(); Console.WriteLine("Started Listening on " + IPAddress.Any.ToString()); Thread t = new Thread(new ThreadStart(MainLoop)); t.IsBackground = true; t.Start(); while (true) { if(tcpListener.Pending()) tcpListener.BeginAcceptTcpClient(new AsyncCallback(AcceptClientConnection), tcpListener); Thread.Sleep(100); } }
private void Receive(int port) { IPAddress ip = IPAddress.Any; MessageBox.Show(ip.ToString()); TcpListener listener = new TcpListener(ip, port); listener.Start(); byte[] data = new byte[1024]; int recBytes; while (true) { if (listener.Pending()) { client = listener.AcceptTcpClient(); NetworkStream nStream = client.GetStream(); Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); Nullable<bool> result = dlg.ShowDialog(); string filename = String.Empty; if (result == true) { filename = dlg.FileName; } if (!string.IsNullOrEmpty(filename)) { int totalrecbytes = 0; FileStream Fs = new FileStream (filename, FileMode.OpenOrCreate, FileAccess.Write); while ((recBytes = nStream.Read (data, 0, data.Length)) > 0) { Fs.Write(data, 0, recBytes); totalrecbytes += recBytes; } Fs.Close(); } nStream.Close(); client.Close(); } } }
private static void Listen(object state) { if (_listener.Pending()) { Broadcast(_listener, new MessageEventArgs(new Message("Connection Found."))); System.Net.Sockets.TcpClient client = (System.Net.Sockets.TcpClient)_listener.AcceptTcpClientAsync().AsyncState; if (client != null) { NetworkStream ns = client.GetStream(); byte[] bytes = new byte[256]; string data; int i; while ((i = ns.Read(bytes, 0, bytes.Length)) != 0) { data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); Broadcast(_listener, new MessageEventArgs(new Message(data))); } client.Dispose(); } } }
public Daemon(JobQueue queue, string hostName) { GearmanServer.Log.Info("Server listening on port 4730"); TCPServer = new System.Net.Sockets.TcpListener(4730); workers = new ConcurrentDictionary <string, List <Connection> >(); while (true) { TCPServer.Start(); if (TCPServer.Pending()) { try { new ConnectionHandler(TCPServer.AcceptTcpClient(), queue, hostName, workers); } catch (Exception e) { GearmanServer.Log.Error("Exception waiting for connection: ", e); } } System.Threading.Thread.Sleep(1); } }
/// <summary> A private variation on <code>accept()</code> that also has an argument /// indicating that the process we are waiting for is an AIR application. If /// it is, then we can sometimes give slightly better error messages (see bug /// FB-7544). /// /// </summary> /// <param name="isAIRapp">if <code>true</code>, then the process we are waiting for /// is an AIR application. This is only used to give better error /// messages in the event that we can't establish a connection to /// that process. /// </param> private Session accept(IProgress waitReporter, bool isAIRapp) { // get timeout int timeout = getPreference(SessionManager.PREF_ACCEPT_TIMEOUT); int totalTimeout = timeout; int iterateOn = 100; PlayerSession session = null; try { m_processDead = false; m_serverSocket.Server.ReceiveTimeout = iterateOn; // Wait 100ms per iteration. We have to do that so that we can report how long // we have been waiting. System.Net.Sockets.TcpClient s = null; while (s == null && !m_processDead) { try { if (m_serverSocket.Pending()) { s = m_serverSocket.AcceptTcpClient(); } else { System.Threading.Thread.Sleep(iterateOn); timeout -= iterateOn; if (timeout < 0) { throw new IOException(); } } } catch (IOException ste) { timeout -= iterateOn; if (timeout < 0 || m_serverSocket == null || !m_serverSocket.Server.Connected) { throw ste; // we reached the timeout, or someome called stopListening() } } // Tell the progress monitor we've waited a little while longer, // so that the Eclipse progress bar can keep chugging along if (waitReporter != null) { waitReporter.setProgress(totalTimeout - timeout, totalTimeout); } } if (s == null && m_processDead) { IOException e = null; String detailMessage = LocalizationManager.getLocalizedTextString("processTerminatedWithoutDebuggerConnection"); //$NON-NLS-1$ if (m_processMessages != null) { String commandLineMessage = m_processMessages.ToString(); if (commandLineMessage.Length > 0) { e = new CommandLineException(detailMessage, m_launchCommand, commandLineMessage, m_processExitValue); } } if (e == null) { if (isAIRapp) { // For bug FB-7544: give the user a hint about what might have gone wrong. detailMessage += s_newline; detailMessage += LocalizationManager.getLocalizedTextString("maybeAlreadyRunning"); //$NON-NLS-1$ } e = new IOException(detailMessage); } throw e; } /* create a new session around this socket */ session = PlayerSession.createFromSocket(s); // transfer preferences session.Preferences = m_prefs; } catch (NullReferenceException) { throw new SocketException(); //$NON-NLS-1$ } finally { m_processMessages = null; m_launchCommand = null; } return(session); }
private void threadMethod(object threadStart) { ConfigureListener.Config config = (ConfigureListener.Config)threadStart; try { lock (_listenerLock) { _listener = new System.Net.Sockets.TcpListener(config.Nic, config.Port); _listener.Start(); } } catch (Exception se) { setStatus("Error: " + se.Message); stopListener(); } byte[] bytes = new byte[256]; while (true) { try { if (_listener == null) { return; } if (!_listener.Pending()) { setStatus("Waiting for a connection... on " + _listener.LocalEndpoint); Thread.Sleep(500); continue; } using (_client = _listener.AcceptTcpClient()) using (NetworkStream stream = _client.GetStream()) { setStatus(string.Format("Connected, {1} -> {0}", _client.Client.LocalEndPoint, _client.Client.RemoteEndPoint)); int i; while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { string data = config.Encoding.GetString(bytes, 0, i); Dispatcher.Invoke(new Action(() => showData(data))); // data = data.ToUpper(); // byte[] msg = Encoding.ASCII.GetBytes(data); // stream.Write(msg, 0, msg.Length); // Console.WriteLine("Sent: {0}", data); } } } catch (Exception se) { setStatus("Error: " + se.Message); } } // finally // { // stopListener(); // } }