public ServerContext(int port, int maxclients, ref List<string> TextStack, string OwnIP) { BeginSendUdpServerCallback = new AsyncCallback(OnBeginSendUdpServerCallbackFinished); ServerMessage = System.Text.Encoding.ASCII.GetBytes("OK:" + OwnIP); UdpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 8011)); //da bei xp fehler UdpServer.JoinMulticastGroup(BroadcastServer.Address); UdpServer.BeginSend(ServerMessage, ServerMessage.Length, BroadcastServer, BeginSendUdpServerCallback, null); MaxClients = maxclients; Ip = IPAddress.Any; this.Port = port; listener = new TcpListener(Ip, Port); Clients = new List<ClientContext>(MaxClients); listener.Start(); BeginAcceptSocketCallback = new AsyncCallback(OnClientConnected); this.TextStack = TextStack; }
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()); } }
//Connect to the client public void connect() { if (!clientConnected) { IPAddress ipAddress = IPAddress.Any; TcpListener listener = new TcpListener(ipAddress, portSend); listener.Start(); Console.WriteLine("Server is running"); Console.WriteLine("Listening on port " + portSend); Console.WriteLine("Waiting for connections..."); while (!clientConnected) { s = listener.AcceptSocket(); s.SendBufferSize = 256000; Console.WriteLine("Connection accepted from " + s.RemoteEndPoint); byte[] b = new byte[65535]; int k = s.Receive(b); ASCIIEncoding enc = new ASCIIEncoding(); Console.WriteLine("Received:" + enc.GetString(b, 0, k) + ".."); //Ensure the client is who we want if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete") { clientConnected = true; Console.WriteLine(enc.GetString(b, 0, k)); } } } }
public void StartListening() { R = RowacCore.R; R.Log("[Listener] Starting TCP listener..."); TcpListener listener = new TcpListener(IPAddress.Any, 28165); listener.Start(); while (true) { try { var client = listener.AcceptSocket(); #if DEBUG R.Log("[Listener] Connection accepted."); #endif var childSocketThread = new Thread(() => { byte[] data = new byte[1048576]; // for screenshots and tasklists int size = 0; while (client.Available != 0) size += client.Receive(data, size, 256, SocketFlags.None); // TODO: increase reading rate from 256? client.Close(); string request = Encoding.ASCII.GetString(data, 0, size); #if DEBUG R.Log(string.Format("Received [{0}]: {1}", size, request)); #endif ParseRequest(request); }); childSocketThread.Start(); } catch (Exception ex) { R.LogEx("ListenerLoop", ex); } } }
public void ShouldAllowRestart() { var listener = new TcpListener(9995); listener.Start(); listener.Stop(); listener.Start(); Assert.AreEqual(ListenerStatus.Listening, listener.Status); }
public void StartServer() { if (m_SourceForm == null) { m_SynchronizingObject = m_SourceForm; } //* Find the IPV4 address of this computer string LocalComputerName = System.Net.Dns.GetHostName(); //* same as My.Computer.Name System.Net.IPAddress localAddr = GetIPv4Address(LocalComputerName); if (localAddr == null) { localAddr = System.Net.IPAddress.Parse("127.0.0.1"); } try { server = new TcpListener(localAddr, m_TCPPort); server.Start(); server.BeginAcceptTcpClient(ConnectionAccepted, server); } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } }
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)) { } } }
/// <summary> /// Starts listening for clients /// </summary> /// <param name="ipAddress">The IP address to use</param> /// <param name="port">The port on which to listen</param> public void Start(IPAddress ipAddress, int port) { _server = new TcpListener(ipAddress, port); _server.Start(); _listenProc = W.Threading.Thread.Create(ListenForClientsProc, ListenForClientsProc_OnComplete); IsListening = true; }
/// <summary> /// Starts accepting connections. /// </summary> public void Start() { if (disposed) { throw new ObjectDisposedException(this.ToString()); } // This is equivalent to the behavior of TcpListener.Create in .NET 4.5. listener = new Net.TcpListener(IPAddress.Any, port); //listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0); listener.Start(); listenerSubscription = Observable .FromAsync(() => listener.AcceptTcpClientAsync()) .Repeat() .Select(client => new ReactiveSocket(client)) .Subscribe(socket => { connections.Add(socket); observable.OnNext(socket); IDisposable disposeSubscription = Observable.FromEventPattern <EventHandler, EventArgs>( h => socket.Disposed += h, h => socket.Disposed -= h) .FirstAsync().Subscribe(x => { connections.Remove(socket); }); this.socketDisposable.Add(disposeSubscription); }); }
protected override EventResult OnConnectBusy() { var addr_family = (devp_.AddressFamily.Value == AddressFamilyType.IPv6) ? (AddressFamily.InterNetworkV6) : (AddressFamily.InterNetwork); try { /* ソケット生成 + バインド */ switch (devp_.LocalBindMode.Value) { case BindModeType.INADDR_ANY: local_ep_text_ = string.Format("INADDR_ANY:{0}", devp_.LocalPortNo.Value); tcp_listener_ = new TcpListener((addr_family == AddressFamily.InterNetworkV6) ? (IPAddress.IPv6Any) : (IPAddress.Any), (ushort)devp_.LocalPortNo.Value); break; case BindModeType.SelectAddress: /* 選択中のアドレスファミリと異なる設定の場合はエラー */ if (devp_.LocalIpAddress.Value.AddressFamily != addr_family) { return(EventResult.Error); } local_ep_text_ = string.Format("{0}:{1}", devp_.LocalIpAddress.Value, devp_.LocalPortNo.Value); tcp_listener_ = new TcpListener(devp_.LocalIpAddress.Value, (ushort)devp_.LocalPortNo.Value); break; } /* 待ち受け開始 */ tcp_listener_.Start((int)devp_.Capacity.Value); return(EventResult.Success); } catch { return(EventResult.Error); } }
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 async Task Start(string remoteServerIp, ushort remoteServerPort, ushort localPort, string localIp) { //var clients = new ConcurrentDictionary<IPEndPoint, TcpClient>(); IPAddress localIpAddress = string.IsNullOrEmpty(localIp) ? IPAddress.IPv6Any : IPAddress.Parse(localIp); var server = new System.Net.Sockets.TcpListener(new IPEndPoint(localIpAddress, localPort)); server.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); server.Start(); Console.WriteLine($"TCP proxy started {localPort} -> {remoteServerIp}|{remoteServerPort}"); while (true) { try { var remoteClient = await server.AcceptTcpClientAsync(); remoteClient.NoDelay = true; new TcpClient(remoteClient, new IPEndPoint(IPAddress.Parse(remoteServerIp), remoteServerPort)); } catch (Exception) { } } }
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); } } }
public async void ListenAsync(string ip, int port) { if (Listening) { throw new Exception("Listening"); } Listening = true; server = new System.Net.Sockets.TcpListener(IPAddress.Parse(ip), port); server.Start(); ListeningStarted(this, server); Env.Print($"listening: {server.LocalEndpoint.ToString()}"); try { while (true) { Env.Print("waiting for a connection"); var client = await server.AcceptTcpClientAsync(); Env.Print("one incoming tcp connection"); var session = new TcpClientSession(client); NewSession.Invoke(this, session); TcpClientAccepted?.Invoke(this, session); session.Receive(); } } catch (Exception ex) { Env.Print(ex.Message); } }
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(); }
private void startServer() { try { server = new TcpListener(IPAddress.Any, 8888); server.Start(); stopBtn.Enabled = true; startBtn.Enabled = false; txtReceive.AppendText(">> Waiting For Connection...\n"); if (InvokeRequired) { this.Invoke(new Action(() => AcceptClients())); return; } AcceptClients(); STR = new StreamReader(client.GetStream()); STW = new StreamWriter(client.GetStream()); STW.AutoFlush = true; txtReceive.AppendText("\n**Connection Established**\n"); txtReceive.AppendText("==========\n"); receivingWorker.RunWorkerAsync(); sendingWorker.WorkerSupportsCancellation = true; receivingWorker.WorkerSupportsCancellation = true; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public LoopbackTcpStream(params byte[] initialStagedReadBytes) { var tcpListener = new SystemTcpListener(IPAddress.Loopback, 0); try { tcpListener.Start(); var clientSocket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; clientSocket.Connect(tcpListener.LocalEndpoint); this._senderStream = new NetworkStream(clientSocket, true); var receiverSocket = tcpListener.AcceptSocket(); this._receiverStream = new NetworkStream(receiverSocket, true); this.LocalEndPoint = receiverSocket.LocalEndPoint; this.RemoteEndPoint = receiverSocket.RemoteEndPoint; this._writtenBytes = new BufferBlock <byte>(); } finally { tcpListener.Stop(); } if (initialStagedReadBytes != null) { this.StageReadBytes(initialStagedReadBytes); } }
public const int MAX_PORT = 65535; // highest port allocatable /// <summary>Finds first available port starting at start_port and returns server socket </summary> public static System.Net.Sockets.TcpListener createServerSocket(int start_port) { System.Net.Sockets.TcpListener ret = null; while (true) { try { System.Net.Sockets.TcpListener temp_tcpListener; temp_tcpListener = new System.Net.Sockets.TcpListener(start_port); temp_tcpListener.Start(); ret = temp_tcpListener; } catch (System.Net.Sockets.SocketException bind_ex) { start_port++; continue; } catch (System.IO.IOException io_ex) { } break; } return(ret); }
private void StartListen2() { //Create an instance of TcpListener to listen for TCP connection. var tcpListener = new TcpListener(SampleTcpPort); try { while (true) { tcpListener.Start(); //Program blocks on Accept() until a client connects. Socket soTcp = tcpListener.AcceptSocket(); Console.Message = ("SampleClient is connected through TCP."); OnChanged(EventArgs.Empty); var received = new Byte[512]; soTcp.Receive(received, received.Length, 0); String dataReceived = System.Text.Encoding.ASCII.GetString(received); Console.Message=(dataReceived); String returningString = "The Server got your message through TCP: " + dataReceived; OnChanged(EventArgs.Empty); Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes (returningString.ToCharArray()); //Returning a confirmation string back to the client. soTcp.Send(returningByte, returningByte.Length, 0); } } catch (SocketException se) { Console.Message = ("A Socket Exception has occurred!" + se); OnChanged(EventArgs.Empty); } }
void HandleThreadStart() { try { TCL = new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 10112)); TCL.Start(); do { try { System.Net.Sockets.Socket S = TCL.AcceptSocket(); FeuerwehrCloud.Helper.Logger.WriteLine("| < [FAX] *** Incoming notification"); S.Blocking = false; S.BeginReceive(buffer, 0, DEFAULT_SIZE - dataRecieved, System.Net.Sockets.SocketFlags.None, new AsyncCallback(HandleAsyncCallback), S); if (IsTerminating) { break; } } catch (Exception e2x) { } } while (true); } catch (Exception ex) { if (ex.Message.Contains("already in use")) { FeuerwehrCloud.Helper.Logger.WriteLine("Kann FeuerwehrCloud-Server FaxModul nicht starten!"); } } }
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()); } }
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 static void InitalizeListener(int port) { _listener = new System.Net.Sockets.TcpListener(_ip, port); _listener.Start(); System.Threading.Timer _t = new System.Threading.Timer(Listen, null, 0, 100); }
public async Task Start(IPAddress iP, int port) { tcpListener = new TcpListener(iP, port); connectedTcpClient = null; source = new CancellationTokenSource(); token = source.Token; tcpListener.Start(); EventHandler serverStartedHandler = ServerStarted; if (serverStartedHandler != null) { serverStartedHandler(this, null); } connectedTcpClient = await Task.Run(() => tcpListener.AcceptTcpClientAsync(), token); if (connectedTcpClient != null) { EventHandler clientConnectedHandler = ClientConnected; if (clientConnectedHandler != null) { clientConnectedHandler(this, null); } var c = new Thread(() => ServerReceive()); c.Start(); } }
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(); }
public void GetAvailableTcpPortTest() { int Port = NetworkUtilities.GetAvailableTcpPort(); var Listener = new TcpListener(IPAddress.Parse("127.0.0.1"), Port); Listener.Start(); Listener.Stop(); }
public Server(IPAddress ip, int port) { console = new consoleUI(); int maxPlayers = 3; player = new Client[maxPlayers]; reservedIDs = new Boolean[maxPlayers]; for (int i = 0; i < reservedIDs.Length; i++) { reservedIDs[i] = false; } try { tcpListener = new TcpListener(IPAddress.Any, port); tcpListener.Start(); } catch (Exception exp) { console.consoleW("Beim Versuch der Auflösung der Addresse: " + ip.ToString() + " enstand folgender Fehler:\r\n" + exp.Message, "error"); while (true) ; } }
// http://stackoverflow.com/questions/7690520/c-sharp-networking-tcpclient void TcpListenerLoop() { try { m_tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Parse(m_privateIP), m_port); m_tcpListener.Start(); Console.WriteLine($"*TcpListener is listening on port {m_privateIP}:{m_port}."); while (true) { var tcpListenerCurrentClientTask = m_tcpListener.AcceptTcpClientAsync(); var tcpClient = tcpListenerCurrentClientTask.Result; // Task.Result is blocking. OK. Console.WriteLine($"TcpListenerLoop.NextClientAccepted."); Utils.Logger.Info($"TcpListenerLoop.NextClientAccepted."); if (Utils.MainThreadIsExiting.IsSet) return; // if App is exiting gracefully, don't start new thread m_tcpClientQueue.Add(tcpClient); // If it is a long processing, e.g. reading the TcpClient, do it in a separate thread. If it is just added to the queue, don't start a new thread //(new Thread((x) => ReadTcpClientStream(x)) { IsBackground = true }).Start(tcpClient); // read the BinaryReader() and deserialize in separate thread, so not block the TcpListener loop } } catch (Exception e) // Background thread can crash application. A background thread does not keep the managed execution environment running. { if (Utils.MainThreadIsExiting.IsSet) return; // if App is exiting gracefully, this Exception is not a problem Utils.Logger.Error("Not expected Exception. We send email by StrongAssert and rethrow exception, which will crash App. TcpListenerLoop. " + e.Message + " ,InnerException: " + ((e.InnerException != null) ? e.InnerException.Message : "")); StrongAssert.Fail(Severity.ThrowException, "Not expected Exception. We send email by StrongAssert and rethrow exception, which will crash App. TcpListenerLoop. VirtualBroker: manual restart is needed."); throw; // if we don't listen to TcpListener any more, there is no point to continue. Crash the App. } }
public Acceptor(ushort pPort, Action<Socket> pAction = null) { _listener = new TcpListener(IPAddress.Any, pPort); _listener.Start(); _action = pAction; StartAccept(); }
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 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) { } }
public async Task Start(string remoteServerIp, ushort remoteServerPort, ushort localPort, string localIp, byte[] byteMapClient2Setver, byte[] byteMapSetver2Client) { //var clients = new ConcurrentDictionary<IPEndPoint, TcpClient>(); IPAddress localIpAddress = string.IsNullOrEmpty(localIp) ? IPAddress.IPv6Any : IPAddress.Parse(localIp); var server = new System.Net.Sockets.TcpListener(new IPEndPoint(localIpAddress, localPort)); server.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); server.Start(); Console.WriteLine($"TCP proxy started {localPort} -> {remoteServerIp}|{remoteServerPort}"); while (true) { try { var remoteClient = await server.AcceptTcpClientAsync(); remoteClient.NoDelay = true; var ips = await Dns.GetHostAddressesAsync(remoteServerIp); new TcpClient(remoteClient, new IPEndPoint(ips.First(), remoteServerPort), byteMapClient2Setver, byteMapSetver2Client); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex); Console.ResetColor(); } } }
/// <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 Servidor() { Console.WriteLine ("Iniciando servidor"); ipAddress = Dns.GetHostEntry("localhost").AddressList[0]; listener = new TcpListener (ipAddress, porta); listener.Start (); }
public void Start() { _stop = false; _listener = new TcpListener(IPAddress.Any, _port); _listener.Start(); _listener.BeginAcceptSocket(OnAcceptSocket, null); }
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); } }
// starts up the listener thread and heartbeat public bool Start() { bool worked = false; int attempts = 0; int attemptsMax = 20; int port = world.config.GetInt( "Port" ); do { try { listener = new TcpListener( IPAddress.Any, port ); listener.Start(); worked = true; } catch( Exception ex ) { world.log.Log( "Could not start listening on port {0}, trying next port. ({1})", LogType.Error, port, ex.Message ); port++; attempts++; } } while( !worked && attempts < attemptsMax ); if( !worked ) { world.log.Log( "Could not start listening after {0} tries. Giving up!", LogType.FatalError, attemptsMax ); return false; } sessions = new List<Session>(); world.log.Log( "Server.Run: now accepting connections at port {0}.", LogType.Debug, port ); return true; }
public HttpServer(int port) { prefixes.TryAdd( "/favicon.ico", new StaticHandler( new ResourceResponse(HttpCode.Ok, "image/icon", "favicon")) ); prefixes.TryAdd( "/static/browse.css", new StaticHandler( new ResourceResponse(HttpCode.Ok, "text/css", "browse_css")) ); RegisterHandler(new IconHandler()); listener = new TcpListener(new IPEndPoint(IPAddress.Any, port)); listener.Server.Ttl = 32; listener.Server.UseOnlyOverlappedIO = true; listener.Start(); RealPort = (listener.LocalEndpoint as IPEndPoint).Port; NoticeFormat( "Running HTTP Server: {0} on port {1}", Signature, RealPort); ssdpServer = new SsdpHandler(); timeouter.Elapsed += TimeouterCallback; timeouter.Enabled = true; Accept(); }
public TCPServer(int port) { listener = new TcpListener(IPAddress.Any, port); player = new AI(this); listener.Start(); Start(); }
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(); } }
static void BackupProcess() { Console.WriteLine("I am backup!"); IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0]; TcpListener listener = new TcpListener(ipAddress, port); listener.Start(); Socket sock = listener.AcceptSocket(); Stream str = new NetworkStream(sock); StreamReader sr = new StreamReader(str); string line = "-1"; try { while (true) line = sr.ReadLine(); } catch(IOException) { sr.Close(); listener.Stop(); PrimaryProcess(Convert.ToInt32(line) + 1); } }
public const int MAX_PORT = 65535; // highest port allocatable /// <summary>Finds first available port starting at start_port and returns server socket </summary> public static System.Net.Sockets.TcpListener createServerSocket(int start_port) { System.Net.Sockets.TcpListener ret = null; while (true) { try { System.Net.Sockets.TcpListener temp_tcpListener; temp_tcpListener = new System.Net.Sockets.TcpListener(start_port); temp_tcpListener.Start(); ret = temp_tcpListener; } catch (System.Net.Sockets.SocketException bind_ex) { //Trace.error("util.createServerSocket()",bind_ex.Message); start_port++; continue; } catch (System.IO.IOException io_ex) { //Trace.error("Util.createServerSocket():2" + io_ex.Message); } break; } return(ret); }
public Server() { config = new INIReader(System.IO.File.ReadAllLines("config.ini")); chat = new ServerChat(); instance = this; vehicleController = new ServerVehicleController(); api = new ServerApi(this); gamemodeManager = new GamemodeManager(api); gamemodeManager.loadFromFile("gamemodes/" + config.getString("gamemode")); server = new TcpListener(IPAddress.Any, config.getInt("game_port")); server.Start(); server.BeginAcceptTcpClient(onIncomingConnection, null); playerpool = new List<ServerPlayer>(); Timer timer = new Timer(); timer.Elapsed += onBroadcastTimer; timer.Interval = config.getInt("broadcast_interval"); timer.Enabled = true; timer.Start(); UDPStartPort = config.getInt("udp_start_port"); Timer timer_slow = new Timer(); timer_slow.Elapsed += timer_slow_Elapsed; timer_slow.Interval = config.getInt("slow_interval"); timer_slow.Enabled = true; timer_slow.Start(); http_server = new HTTPServer(); Console.WriteLine("Started game server on port " + config.getInt("game_port").ToString()); Console.WriteLine("Started http server on port " + config.getInt("http_port").ToString()); }
public PcapTcpStream(ushort localTcpPort, bool useSsl, int idleTimeoutMilliSeconds) : this(useSsl, idleTimeoutMilliSeconds) { this.socketState = TcpSocketState.Closed; this.tcpListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, (int)localTcpPort); tcpListener.Start(); this.socketState = TcpSocketState.Listening; }
public int FindFreePort(int startingPort) { Exception lastException = null; for (int i = startingPort; i < 65535; i++) { try { var listener = new TcpListener(IPAddress.Loopback, i); listener.Start(); listener.Stop(); logger.Debug("Found free port: {0}", i); return i; } catch (SocketException e) { if (e.SocketErrorCode == SocketError.AddressAlreadyInUse) lastException = e; else throw; } } throw lastException; }
// 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(); }
//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(); } }
public ServerBase(string ip, int port) { var bindIP = IPAddress.None; if (!IPAddress.TryParse(ip, out bindIP)) { Log.Normal($"Server can't be started: Invalid IP-Address ({ip})"); Console.ReadKey(true); Environment.Exit(0); } try { listener = new TcpListener(bindIP, port); listener.Start(); if (isRunning = listener.Server.IsBound) new Thread(AcceptConnection).Start(200); } catch (Exception ex) { ExceptionLog.Write(ex); Log.Error(ex.Message); } }
public async Task ReadLineAsync_ThrowsOnConnectionClose() { TcpListener listener = new TcpListener(IPAddress.Loopback, 0); try { listener.Start(); Task<TcpClient> acceptTask = listener.AcceptTcpClientAsync(); TcpClient client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); using (TcpClient serverTcpClient = await acceptTask) { TcpClientConnectionChannel channel = new TcpClientConnectionChannel(serverTcpClient); client.Dispose(); await Assert.ThrowsAsync<ConnectionUnexpectedlyClosedException>(async () => { await channel.ReadLineAsync(); }); } } finally { listener.Stop(); } }
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()); } }
/// <summary> /// Constructor of the TCP service object /// </summary> /// <param name="port">TCP port number</param> public TCPService(int port) { TcpListener tempTCPListener; tempTCPListener = new TcpListener(System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName())[0], port); tempTCPListener.Start(); serverSocket = tempTCPListener; // serverSocket.setReuseAddress(true); // serverSocket.setLoopbackMode(false); // true *disables* loopback acceptThread = new Thread(AcceptThreadRun); acceptThread.IsBackground = true; acceptThread.Start(); long inittime = DateTime.Now.Ticks / 10000; long starttime = DateTime.Now.Ticks / 10000; while (true) { try { System.Threading.Thread.Sleep(1000); } catch (System.Threading.ThreadInterruptedException) { } long endtime = System.DateTime.Now.Ticks / 10000; double dt = (endtime - starttime) / 1000.0; starttime = endtime; Console.WriteLine("{0,10:N} : {1,10:N} kB/s, {2:D} clients", (endtime - inittime) / 1000.0, bytesCount / 1024.0 / dt, clients.Count); bytesCount = 0; } }
public void ModbusTcpSlave_ConnectionClosesGracefully() { TcpListener slaveListener = new TcpListener(ModbusMasterFixture.TcpHost, ModbusMasterFixture.Port); slaveListener.Start(); ModbusTcpSlave slave = ModbusTcpSlave.CreateTcp(ModbusMasterFixture.SlaveAddress, slaveListener); Thread slaveThread = new Thread(slave.Listen); slaveThread.IsBackground = true; slaveThread.Start(); using (TcpClient masterClient = new TcpClient(ModbusMasterFixture.TcpHost.ToString(), ModbusMasterFixture.Port)) { ModbusIpMaster master = ModbusIpMaster.CreateIp(masterClient); master.Transport.Retries = 0; bool[] coils = master.ReadCoils(1, 1); Assert.AreEqual(1, coils.Length); Assert.AreEqual(1, slave.Masters.Count); } // give the slave some time to remove the master Thread.Sleep(50); Assert.AreEqual(0, slave.Masters.Count); slaveListener.Stop(); }
public ServidorTCP(int puerto) { listener = new System.Net.Sockets.TcpListener(IPAddress.Any, puerto); //Esperar peticiones de conexión listener.Start(); listener.BeginAcceptTcpClient(new AsyncCallback(ComprobarClienteConectado), null); }
public void Start() { IPEndPoint ip = new IPEndPoint(IPAddress.Any, _port); _listener = new System.Net.Sockets.TcpListener(ip); _listener.Start(); _listener.BeginAcceptTcpClient(AcceptCallback, _listener); }
public void Listen(string listenAddress, int port) { RLib.WatchLog.Loger.Log("正在运行", ""); tcpl = new System.Net.Sockets.TcpListener(IPAddress.Parse(listenAddress), port); tcpl.Start(); StartAccept(); StartSend(); ReadDataThread(); }
/// <summary> /// Constructor. /// </summary> /// <param name="port">the port on which to accept incoming connections /// </param> /// <exception cref="System.IO.IOException"> if an IO error occurs /// </exception> public TCPMessageChannelAcceptor(ConnectionInfo info) { System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(info.Addr); System.Net.IPAddress ipAddress = System.Net.Dns.GetHostEntry(hostEntry.HostName).AddressList[0]; serverSocket = new System.Net.Sockets.TcpListener(ipAddress, info.Port); serverSocket.Start(); closed = false; }
public SingleMessageTcpListener(int port) { if (port < 1 || port == 80) { throw new ArgumentOutOfRangeException("Expected a valid port number, > 0, not 80"); } _port = port; _tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, _port); _tcpListener.Start(); }
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()); } }
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()); } }
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); } }