private void asyncSocket_DidRead(AsyncSocket sender, byte[] data, long tag) { String msg = null; try { msg = Encoding.UTF8.GetString(data); #if IS_MULTITHREADED object[] args = { }; this.BeginInvoke(new LogMessageDelegate(LogMessage), msg, args); #else LogMessage(msg); #endif } catch(Exception e) { #if IS_MULTITHREADED object[] args = { e }; this.BeginInvoke(new LogMessageDelegate(LogError), "Error converting received data into UTF-8 String: {0}", args); #else LogError("Error converting received data into UTF-8 String: {0}", e); #endif } // Even if we were unable to write the incoming data to the log, // we're still going to echo it back to the client. sender.Write(data, -1, 0); }
private void asyncSocket_DidClose(AsyncSocket sender) { LogInfo("Disconnected from host"); asyncSocket = null; CreateAndSetupAsyncSocket(); fetchButton.Enabled = true; sslCheckBox.Enabled = true; }
private void asyncSocket_DidClose(AsyncSocket sender) { #if IS_MULTITHREADED lock (connectedSockets) { connectedSockets.Remove(sender); } #else connectedSockets.Remove(sender); #endif }
public Client(AsyncSocket sock) { socket = sock; socket.DidRead += new AsyncSocket.SocketDidRead(asyncSocket_DidRead); socket.DidWrite += new AsyncSocket.SocketDidWrite(asyncSocket_DidWrite); socket.WillClose += new AsyncSocket.SocketWillClose(asyncSocket_WillClose); socket.DidClose += new AsyncSocket.SocketDidClose(asyncSocket_DidClose); socket.Read(Client.Terminator, 120 * 1000, 1); sessionID = DateTime.Now.Ticks; uuid = null; }
public Form1() { InitializeComponent(); // Create a new instance of Deusty.Net.AsyncSocket listenSocket = new AsyncSocket(); #if IS_MULTITHREADED // Tell AsyncSocket to allow multi-threaded delegate methods // Note: Accepted sockets will automatically inherit this setting as well listenSocket.AllowMultithreadedCallbacks = true; #else // Tell AsyncSocket to invoke its delegate methods on our form thread // Note: Accepted sockets will automatically inherit this setting as well listenSocket.SynchronizingObject = this; #endif // Register for the events we're interested in listenSocket.DidAccept += new AsyncSocket.SocketDidAccept(listenSocket_DidAccept); // Initialize list to hold connected sockets // We support multiple concurrent connections connectedSockets = new List<AsyncSocket>(); }
public void StopSocket() { listenSocket.Close(); listenSocket = null; }
bool socket_WillConnect(AsyncSocket sender, System.Net.Sockets.Socket socket) { return true; }
void socket_DidWrite(AsyncSocket sender, long tag) { }
/// <summary> /// We have a socket connection /// </summary> /// <param name="sender"></param> /// <param name="address"></param> /// <param name="port"></param> void socket_DidConnect(AsyncSocket sender, System.Net.IPAddress address, ushort port) { if (autologinKey == null) { Log("Authenticating with server", "Connected, waiting for welcome message", "Authenticating ..."); } else { Log("Reconnected to server", "Reconnected with autologin key", "Connected"); } socket.Read(AsyncSocket.CRLFData, -1, 0); }
/// <summary> /// Connect with manually entered info /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonConnect_Click(object sender, EventArgs e) { if (socket != null) { socket.Close(); socket = null; } Log("Connecting ...", null, "Connecting to server"); socket = new AsyncSocket(); socket.WillConnect += new AsyncSocket.SocketWillConnect(socket_WillConnect); socket.DidConnect += new AsyncSocket.SocketDidConnect(socket_DidConnect); socket.WillClose += new AsyncSocket.SocketWillClose(socket_WillClose); socket.DidClose += new AsyncSocket.SocketDidClose(socket_DidClose); socket.DidRead += new AsyncSocket.SocketDidRead(socket_DidRead); socket.DidWrite += new AsyncSocket.SocketDidWrite(socket_DidWrite); ushort thePort; bool isValidPort = ushort.TryParse(textBoxPort.Text, out thePort); if (!isValidPort || !socket.Connect(textBoxAddress.Text, thePort)) { Log(null, "Could not connect to server: AsyncSocket connect failed", "Could not connect to server"); MessageBox.Show("Could not connect to server", "Error"); } }
/// <summary> /// Send a message string /// </summary> /// <param name="message"></param> /// <param name="client"></param> public void SendCommand(String message, AsyncSocket client) { if (message == null) { logWindow.Log = "SendMessage failed: Message string is null"; return; } if (client == null) { Log(null, "SendMessage aborted: Not connected", "Please connect first!"); return; } logWindow.Log = "Sending command: " + message; byte[] data = Encoding.UTF8.GetBytes(message + "\r\n"); client.Write(data, -1, 0); }
/// <summary> /// Handle the facade message /// </summary> /// <param name="message">Message sent from client</param> /// <param name="server">Instance of the socket server</param> /// <param name="client">Socket that sent the message (for return messages)</param> internal static void HandleFacadeMessage(Newtonsoft.Json.Linq.JObject message, SocketServer server, AsyncSocket client) { String action = (string)message["FacadeAction"]; GUIWindow currentPlugin = GUIWindowManager.GetWindow(GUIWindowManager.ActiveWindow); if (action.Equals("get")) { MessageFacade returnMessage = new MessageFacade(); if (currentPlugin.GetType() == typeof(GUIHome)) { GUIMenuControl menu = (GUIMenuControl)currentPlugin.GetControl(50); List<FacadeItem> items = MpFacadeHelper.GetHomeItems(menu); returnMessage.FacadeItems = items; returnMessage.ViewType = "Home"; } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); if (facade != null) { List<FacadeItem> items = MpFacadeHelper.GetFacadeItems(currentPlugin.GetID, 50); returnMessage.ViewType = facade.CurrentLayout.ToString(); returnMessage.FacadeItems = items; } } returnMessage.WindowId = currentPlugin.GetID; server.SendMessageToClient(returnMessage, client); } else if (action.Equals("setselected")) { if (currentPlugin.GetType() == typeof(GUIHome)) { } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); int selected = (int)message["SelectedIndex"]; facade.SelectedListItemIndex = selected; } } else if (action.Equals("getselected")) { if (currentPlugin.GetType() == typeof(GUIHome)) { //TODO: find a way to retrieve the currently selected home button } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); int selected = facade.SelectedListItemIndex; } } else if (action.Equals("getcount")) { if (currentPlugin.GetType() == typeof(GUIHome)) { GUIMenuControl menu = (GUIMenuControl)currentPlugin.GetControl(50); int count = menu.ButtonInfos.Count; } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); int count = facade.Count; } } else if (action.Equals("select")) { int selected = (int)message["SelectedIndex"]; if (currentPlugin.GetType() == typeof(GUIHome)) { GUIMenuControl menu = (GUIMenuControl)currentPlugin.GetControl(50); MenuButtonInfo info = menu.ButtonInfos[selected]; GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, info.PluginID, 0, null); GUIWindowManager.SendThreadMessage(msg); } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); //TODO: is there a better way to select a list item facade.SelectedListItemIndex = selected; new Communication().SendCommand("ok"); } } else if (action.Equals("context")) { int selected = (int)message["SelectedIndex"]; if (currentPlugin.GetType() == typeof(GUIHome)) { GUIMenuControl menu = (GUIMenuControl)currentPlugin.GetControl(50); MenuButtonInfo info = menu.ButtonInfos[selected]; GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, info.PluginID, 0, null); GUIWindowManager.SendThreadMessage(msg); } else { GUIFacadeControl facade = (GUIFacadeControl)currentPlugin.GetControl(50); //TODO: is there a better way to select a list item facade.SelectedListItemIndex = selected; new Communication().SendCommand("info"); } } }
/// <summary> /// Handle the dialog action /// </summary> /// <param name="message">Message from Client</param> internal static void HandleDialogAction(Newtonsoft.Json.Linq.JObject message, SocketServer server, AsyncSocket client) { String action = (string)message["ActionType"]; int dialogId = (int)message["DialogId"]; int index = (int)message["Index"]; if (action.Equals("get")) { if (MpDialogsHelper.IsDialogShown) { MessageDialog msg = MpDialogsHelper.GetDialogMessage(MpDialogsHelper.CurrentDialog); server.SendMessageToClient(msg, client); } else { MessageDialog msg = new MessageDialog(); msg.DialogShown = false; server.SendMessageToClient(msg, client); } } else { if (dialogId == (int)GUIWindow.Window.WINDOW_DIALOG_MENU) { MpDialogMenu diag = MpDialogsHelper.GetDialogMenu(); diag.HandleAction(action, index); } else if (dialogId == (int)GUIWindow.Window.WINDOW_DIALOG_OK) { MpDialogOk diag = MpDialogsHelper.GetDialogOk(); diag.HandleAction(action, index); } else if (dialogId == (int)GUIWindow.Window.WINDOW_DIALOG_YES_NO) { MpDialogYesNo diag = MpDialogsHelper.GetDialogYesNo(); diag.HandleAction(action, index); } else if (dialogId == (int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY) { MpDialogNotify diag = MpDialogsHelper.GetDialogNotify(); diag.HandleAction(action, index); } else if (dialogId == (int)GUIWindow.Window.WINDOW_DIALOG_PROGRESS) { MpDialogProgress diag = MpDialogsHelper.GetDialogProgress(); diag.HandleAction(action, index); } else if (dialogId == (int)GUIWindow.Window.WINDOW_DIALOG_RATING) { MpDialogRating diag = MpDialogsHelper.GetDialogRating(); diag.HandleAction(action, index); } else if (dialogId == MpDialogsHelper.TVSERIES_RATING_ID) { if (WifiRemote.IsAvailableTVSeries) { MpDialogTvSeriesRating diag = MpDialogsHelper.GetDialogMpTvSeriesRating(); diag.HandleAction(action, index); } } else if (dialogId == MpDialogsHelper.TVSERIES_PIN_ID) { if (WifiRemote.IsAvailableTVSeries) { MpDialogTvSeriesPin diag = MpDialogsHelper.GetDialogMpTvSeriesPin(); diag.HandleAction(action, index); } } else if (dialogId == MpDialogsHelper.MOPI_RATING_ID) { if (WifiRemote.IsAvailableMovingPictures) { MpDialogMovingPicturesRating diag = MpDialogsHelper.GetDialogMovingPicturesRating(); diag.HandleAction(action, index); } } else if (dialogId == MpDialogsHelper.MOPI_PIN_ID) { if (WifiRemote.IsAvailableMovingPictures) { MpDialogMovingPicturesPin diag = MpDialogsHelper.GetDialogMovingPicturesPin(); diag.HandleAction(action, index); } } } }
private void asyncSocket_DidConnect(AsyncSocket sender, System.Net.IPAddress address, ushort port) { LogInfo("Connected to {0}:{1}", address, port); // The TCP handshake is now complete, meaning we're connected to the remote host. if (sslCheckBox.Checked) { // We want to create a secure SSL/TLS connection. // So we need to start the TLS handshake. // The StartTLSAsClient method takes 3 parameters. // The first is mandatory, the second two are optional. // Param 1: The expected server name on the remote certificate. // Param 2: Callback to allow you to explicityly check the remote certificate for validation purposes. // Param 3: Callback to allow you to choose your own local certificate. // The deusty certificate is a self-signed certificate. // Self-signed certificates are obviously rejected by default. // So we setup a callback in order to accept it. RemoteCertificateValidationCallback rcvc = new RemoteCertificateValidationCallback(asyncSocket_RemoteCertificateValidationCallback); asyncSocket.StartTLSAsClient(FETCH_SSL_NAME, rcvc, null); } else { // Not using TLS, so immediatley send the http request SendRequest(); } }
private void CreateAndSetupAsyncSocket() { // Create a new instance of Deusty.Net.AsyncSocket asyncSocket = new AsyncSocket(); // Tell AsyncSocket to invoke its delegate methods on our form thread asyncSocket.SynchronizingObject = this; // Register for the events we're interested in asyncSocket.DidConnect += new AsyncSocket.SocketDidConnect(asyncSocket_DidConnect); asyncSocket.DidSecure += new AsyncSocket.SocketDidSecure(asyncSocket_DidSecure); asyncSocket.DidWrite += new AsyncSocket.SocketDidWrite(asyncSocket_DidWrite); asyncSocket.DidRead += new AsyncSocket.SocketDidRead(asyncSocket_DidRead); asyncSocket.DidReadPartial += new AsyncSocket.SocketDidReadPartial(asyncSocket_DidReadPartial); asyncSocket.WillClose += new AsyncSocket.SocketWillClose(asyncSocket_WillClose); asyncSocket.DidClose += new AsyncSocket.SocketDidClose(asyncSocket_DidClose); }
private void socket_DidRead(AsyncSocket sender, byte[] data, long tag) { try { string msg = Encoding.UTF8.GetString(data); // Get json object JObject message = JObject.Parse(msg); string type = (string)message["Type"]; if (type != null) { switch (type) { // {"Type":"welcome","Server_Version":4,"AuthMethod":0} case "welcome": HandleWelcomeMessage(msg); break; // {"Type":"authenticationresponse","Success":true,"ErrorMessage":null} case "authenticationresponse": HandleAuthenticationResponse(msg); break; case "dialogResult": HandleDialogResult(msg); break; case "dialog": HandleDialogMessage(msg); break; } } } catch (Exception e) { Log.Error("WifiRemoteClient: Communication error", e); } // Continue listening sender.Read(AsyncSocket.CRLFData, -1, 0); }
/// <summary> /// Send a message object /// </summary> /// <param name="message"></param> /// <param name="client"></param> public void SendCommand(IMessage message, AsyncSocket client) { if (message == null) { logWindow.Log = "SendMessage failed: IMessage object is null"; return; } if (autologinKey != null) { message.AutologinKey = autologinKey; } string messageString = JsonConvert.SerializeObject(message); SendCommand(messageString, client); }
/// <summary> /// Allows invoke options to be inherited from another AsyncSocket. /// This is usefull when accepting connections. /// </summary> /// <param name="fromSocket"> /// AsyncSocket object to copy invoke options from. /// </param> protected void InheritInvokeOptions(AsyncSocket fromSocket) { // We set the MultiThreadedCallback property first, // as it has the potential to affect the other properties. AllowMultithreadedCallbacks = fromSocket.AllowMultithreadedCallbacks; AllowApplicationForms = fromSocket.AllowApplicationForms; SynchronizingObject = fromSocket.SynchronizingObject; }
/// <summary> /// Connect to server selected in autodetect list /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonConnectDetected_Click(object sender, EventArgs e) { if (servers.Count <= 0 || listBoxServers.SelectedItem == null) { return; } if (socket != null) { socket.Close(); socket = null; } Log("Connecting ...", null, "Connecting to server"); socket = new AsyncSocket(); socket.WillConnect += new AsyncSocket.SocketWillConnect(socket_WillConnect); socket.DidConnect += new AsyncSocket.SocketDidConnect(socket_DidConnect); socket.WillClose += new AsyncSocket.SocketWillClose(socket_WillClose); socket.DidClose += new AsyncSocket.SocketDidClose(socket_DidClose); socket.DidRead += new AsyncSocket.SocketDidRead(socket_DidRead); socket.DidWrite += new AsyncSocket.SocketDidWrite(socket_DidWrite); if (!socket.Connect(((NetService)listBoxServers.SelectedItem).HostName, (ushort)((NetService)listBoxServers.SelectedItem).Port)) { Log(null, "Could not connect to server: AsyncSocket connect failed", "Could not connect to server"); MessageBox.Show("Could not connect to server", "Error"); } }
// What is going on with the event handler methods below? // // The asynchronous nature of this class means that we're very multithreaded. // But the client may not be. The client may be using a SynchronizingObject, // or has requested we use application forms for invoking. // // A problem arises from this situation: // If a client calls the Disconnect method, then he/she does NOT // expect to receive any other delegate methods after the // call to Diconnect completes. // // Primitive invoking from a background thread will not solve this problem. // So what we do instead is invoke into the same thread as the client, // then check to make sure the socket hasn't been closed, // and then execute the delegate method. protected virtual void OnSocketDidAccept(AsyncSocket newSocket) { // SYNCHRONOUS // This allows the newly accepted socket to register to receive the DidConnect event. if (DidAccept != null) { if (synchronizingObject != null) { object[] args = { newSocket }; synchronizingObject.Invoke(new DoDidAcceptDelegate(DoDidAccept), args); } else if (allowApplicationForms) { System.Windows.Forms.Form appForm = GetApplicationForm(); if (appForm != null) { appForm.Invoke(new DoDidAcceptDelegate(DoDidAccept), newSocket); } } else if (allowMultithreadedCallbacks) { object[] delPlusArgs = { DidAccept, this, newSocket }; eventQueue.Enqueue(delPlusArgs); ProcessEvent(); } } }
void socket_DidClose(AsyncSocket sender) { labelDetail.Text = ""; Log("", "Disconnected", "Disconnected"); }
private void DoDidAccept(AsyncSocket newSocket) { // Threading Notes: // This method is called when using a SynchronizingObject or AppForms, // so method is executed on the same thread that the delegate is using. // Thus, the kClosed flag prevents any callbacks after the delegate calls the close method. if ((flags & kClosed) != 0) return; try { if (DidAccept != null) { DidAccept(this, newSocket); } } catch { } }
void socket_DidRead(AsyncSocket sender, byte[] data, long tag) { String msg = null; try { msg = Encoding.UTF8.GetString(data); logWindow.Log = "Received message: " + msg; this.Focus(); // Get json object JObject message = JObject.Parse(msg); string type = (string)message["Type"]; if (type != null) { // {"Type":"welcome","Server_Version":4,"AuthMethod":0} switch (type) { case "welcome": handleWelcomeMessage((int)message["Server_Version"], (int)message["AuthMethod"]); break; // {"Type":"authenticationresponse","Success":true,"ErrorMessage":null} case "authenticationresponse": // handleAuthenticationResponse((bool)message["Success"], (String)message["ErrorMessage"]); handleAuthenticationResponse((bool)message["Success"], (String)message["ErrorMessage"], (string)message["AutologinKey"]); break; // {"Type":"status","IsPlaying":false,"IsPaused":false,"Title":"","CurrentModule":"Startbildschirm","SelectedItem":""} case "status": handleStatus((bool)message["IsPlaying"], (bool)message["IsPaused"], (string)message["Title"], (string)message["CurrentModule"], (string)message["SelectedItem"]); break; // {"Type":"volume","Volume":37,"IsMuted":false} case "volume": handleVolumeChange((int)message["Volume"], (bool)message["IsMuted"]); break; } } } catch (Exception e) { Log(null, "Communication Error: " + e.Message, null); } // Continue listening sender.Read(AsyncSocket.CRLFData, -1, 0); }
/// <summary> /// Description forthcoming /// </summary> /// <param name="iar"></param> private void socket_DidAccept(IAsyncResult iar) { lock (lockObj) { if ((flags & kClosed) > 0) return; try { Socket socket = (Socket)iar.AsyncState; Socket newSocket = socket.EndAccept(iar); AsyncSocket newAsyncSocket = new AsyncSocket(); newAsyncSocket.InheritInvokeOptions(this); newAsyncSocket.PreConfigure(newSocket); OnSocketDidAccept(newAsyncSocket); newAsyncSocket.PostConfigure(); // And listen for more connections socket.BeginAccept(new AsyncCallback(socket_DidAccept), socket); } catch (Exception e) { CloseWithException(e); } } }
void socket_WillClose(AsyncSocket sender, Exception e) { }
/// <summary> /// Connect with manually entered info /// </summary> public void Connect() { if (socket != null) { socket.Close(); socket = null; } Connected = false; ConnectionFailed = false; Authenticated = false; AuthenticationFailed = false; Log.Info("Setting up WifiRemote connection to {0}:{1}", Address, Port); socket = new AsyncSocket(); socket.DidConnect += new AsyncSocket.SocketDidConnect(socket_DidConnect); socket.DidRead += new AsyncSocket.SocketDidRead(socket_DidRead); socket.AllowMultithreadedCallbacks = true; if (!socket.Connect(Address, 8017)) { Log.Warn("WifiRemoteClient: Could not connect to server, AsyncSocket connect failed"); ConnectionFailed = true; } }
public void StartSocket() { listenSocket = new AsyncSocket(); listenSocket.AllowMultithreadedCallbacks = true; listenSocket.DidAccept += new AsyncSocket.SocketDidAccept(listenSocket_DidAccept); Exception error; if (!listenSocket.Accept(ushort.Parse(Preferences.Instance.Value("port")), out error)) { Logger.Instance.eventLog.WriteEntry(String.Format("Error starting server: {0}", error), EventLogEntryType.Information); return; } PublishBonjour(); }
public void Disconnect() { Connected = false; Authenticated = false; if (socket != null) { socket.Close(); socket = null; } }
private void listenSocket_DidAccept(AsyncSocket sender, AsyncSocket newSocket) { Client client = new Client(newSocket); Clients.Instance.AddClient(client); }
/// <summary> /// We have a socket connection /// </summary> /// <param name="sender"></param> /// <param name="address"></param> /// <param name="port"></param> private void socket_DidConnect(AsyncSocket sender, IPAddress address, ushort port) { Connected = true; ConnectionFailed = false; if (autologinKey == null) { Log.Debug("WifiRemoteClient: Authenticating with server, waiting for welcome message..."); } else { Log.Debug("WifiRemoteClient: Reconnected to server with autologin key"); } socket.Read(AsyncSocket.CRLFData, -1, 0); }