// Constructor public Server(ServerForm form, StartStopServer del, ServerMessageReceived action, ServerMessageResponse actionResponse, AddClientsToServer addClient, RemoveClientsToServer removeClient, SetServerIPAddress serverIPDelegate) { // Create thread _serverThread = new Thread(new ThreadStart(ServerMainThreadFunction)); _serverThread.Name = "Server Main Thread"; _serverThread.Start(); // Create thread for UDP connection _threadSendToClient = new Thread(new ThreadStart(ThreadReceiveResponse)); _threadSendToClient.Name = "Server Thread Listener"; _threadSendToClient.Start(); _parentForm = form; _endActionDelegate = del; _messageReceivedAction = action; _messageResponseAction = actionResponse; _addClientDelegate = addClient; _removeClientDelegate = removeClient; _displayServerIP = serverIPDelegate; // Get directory of job _directoryWork = Directory.GetCurrentDirectory(); // Get local IP address _serverIPAddress = GetPublicIPAddress(); _parentForm.Invoke(_displayServerIP, (object)_serverIPAddress); // How enable port forwarding NATUPNPLib.UPnPNATClass upnpnat = new NATUPNPLib.UPnPNATClass(); _mappingsPort = upnpnat.StaticPortMappingCollection; GetLocalIPAddress(); try { _mappingsPort.Add(_numberOfPortToListen, "TCP", _numberOfPortToListen, GetLocalIPAddress(), true, "CNC TCP Server"); } catch (Exception excp) { MessageBox.Show(excp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // Send action _parentForm.Invoke(this._endActionDelegate, (object)false); return; } }
private void ThreadReceiveResponse() { int nIndex = 0; bool bContinue = true; string totalData = String.Empty; while (bContinue == true) { nIndex = EventWaitHandle.WaitAny(_eventHandleSendToClient); switch (nIndex) { case 0: if (TCPSendData(_fileTosend, _clientIPAddress, _numPortForSend) == false) { MessageBox.Show("TCP Connection failed !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } // Get response totalData = TCPGetData(); if (totalData != null) { // Signal that a message has been received _parentForm.Invoke(this._messageReceivedAction, (Object)(totalData)); } // Close communication CloseTCP(); break; case 1: bContinue = false; break; } } }