/// <summary> /// Callback when a client connects /// </summary> /// <param name="connection">The TCP connection handler</param> /// private void server_OnConnect(tcpServer.TcpServerConnection connection) { // Tell us who has connected Trace.TraceInformation(DateTime.Now + ": TCP - New client connection from {0}", connection.Socket.Client.RemoteEndPoint); Trace.Flush(); }
private void runListener() { while (m_isOpen && m_port >= 0) { try { if (listener.Pending()) { TcpClient socket = listener.AcceptTcpClient(); TcpServerConnection conn = new TcpServerConnection(socket, m_encoding); if (OnConnect != null) { lock (activeThreadsLock) { activeThreads++; } conn.CallbackThread = new Thread(() => { OnConnect(conn); }); conn.CallbackThread.Start(); } lock (connections) { connections.Add(conn); } } else { if (System.Threading.Thread.CurrentThread.IsAlive) { System.Threading.Thread.Sleep(m_idleTime); } } } catch (ThreadInterruptedException) { } //thread is interrupted when we quit catch (Exception e) { if (m_isOpen && OnError != null) { OnError(this, e); } } } }
private void tcpServer1_OnDataAvailable(tcpServer.TcpServerConnection connection) { byte[] data = readStream(connection.Socket); if (data != null) { string dataStr = Encoding.ASCII.GetString(data); invokeDelegate del = () => { logData(false, dataStr); }; Invoke(del); data = null; } }
/// <summary> /// Callback when a when data is available from the connection. /// Parses response and submits an input event to the state machine. /// </summary> /// <param name="connection">The TCP connection handler</param> /// private void server_OnDataAvailable(tcpServer.TcpServerConnection connection) { var TCPSMCommands = new Dictionary <string, Input>(StringComparer.OrdinalIgnoreCase) { { "START", Input.CommandStart }, { "STOP", Input.CommandStop }, { "PAUSE", Input.CommandPause }, { "RESUME", Input.CommandResume }, }; byte[] data = readStream(connection.Socket); if (data != null) { // Remove line endings string dataStr = Encoding.ASCII.GetString(data).TrimEnd('\n', '\r'); Input inputCommand = Input.None; Trace.TraceInformation(DateTime.Now + ": TCP - Rx: " + dataStr); Trace.Flush(); //Fire the command event. if (this.stateMachine != null && TCPSMCommands.TryGetValue(dataStr, out inputCommand)) { // Check the application settings to see if control is enabled. If not, trace and do nothing. if (Properties.Settings.Default.AllowControl) { this.stateMachine.PostInput(inputCommand); } else { Trace.TraceInformation(DateTime.Now + ": Control functionality disabled. Command ignored."); } } else { Trace.TraceInformation(DateTime.Now + ": TCP - Command '{0}' not found", dataStr); Trace.Flush(); TcpSend("TCP-Error: Command not found: " + dataStr); } } }
private void tcpServer_OnDataAvailable(tcpServer.TcpServerConnection connection) { string data = readStream(connection.Socket); string result; if (data != null) { Console.WriteLine(">>Received Data, Message: {0}", data); result = Parser.Parse(data); if (result.Split(',')[0].CompareTo("Broadcast") != 0) { connection.sendData(result); } else { tcpServer.Send(result.Substring(10)); } data = null; } }
private void tcpServer1_OnDataAvailable(tcpServer.TcpServerConnection connection) { byte[] data = readStream(connection.Socket); if (data != null) { string dataStr = Encoding.ASCII.GetString(data); if (dataStr.Contains("openForm1")) { Application.Run(new Form1()); form2.Close(); } else if (dataStr.Contains("openForm2")) { Application.Run(new Form2()); form1.Close(); } else if (dataStr.Contains("closeAll")) { form1.Close(); form2.Close(); } } }
private bool processConnection(TcpServerConnection conn) { bool moreWork = false; if (conn.processOutgoing(m_maxSendAttempts)) { moreWork = true; } if (OnDataAvailable != null && activeThreads < m_maxCallbackThreads && conn.Socket.Available > 0) { lock (activeThreadsLock) { activeThreads++; } conn.CallbackThread = new Thread(() => { OnDataAvailable(conn); }); conn.CallbackThread.Start(); Thread.Yield(); } return(moreWork); }
private void runSender() { while (m_isOpen && m_port >= 0) { try { bool moreWork = false; for (int i = 0; i < connections.Count; i++) { if (connections[i].CallbackThread != null) { try { connections[i].CallbackThread = null; lock (activeThreadsLock) { activeThreads--; } } catch (Exception) { //an exception is thrown when setting thread and old thread hasn't terminated //we don't need to handle the exception, it just prevents decrementing activeThreads } } if (connections[i].CallbackThread != null) { } else if (connections[i].connected() && (connections[i].LastVerifyTime.AddMilliseconds(m_verifyConnectionInterval) > DateTime.UtcNow || connections[i].verifyConnected())) { moreWork = moreWork || processConnection(connections[i]); } else { lock (connections) { TcpServerConnection conn = connections[i]; if (OnDisconnect != null) { lock (activeThreadsLock) { activeThreads++; } conn.CallbackThread = new Thread(() => { OnDisconnect(conn); }); conn.CallbackThread.Start(); } connections.Remove(conn); i--; } } } if (!moreWork) { System.Threading.Thread.Yield(); lock (sem) { foreach (TcpServerConnection conn in connections) { if (conn.hasMoreWork()) { moreWork = true; break; } } } if (!moreWork) { waiting = true; sem.Wait(m_idleTime); waiting = false; } } } catch (ThreadInterruptedException) { } //thread is interrupted when we quit catch (Exception e) { if (m_isOpen && OnError != null) { OnError(this, e); } } } }
private void tcpServer1_OnConnect(tcpServer.TcpServerConnection connection) { invokeDelegate setText = () => lbconnectstate.Text = GT_DataPusher.m_object.Connections.Count > 0? "Connect" : "Not Connect"; Invoke(setText); }
private void HandleMessage(TcpServerConnection connection, string msg) { string[] parts = msg.Split('|'); if (parts[0] == "VERSION") { int version = int.Parse(parts[1]); if (version < Util.version) { serverWindow.PrintLine("<" + GetAlias(connection) + "> attempted to connect with old client version " + version + "."); TrySendMessage(connection, "ERROR|OLD_CLIENT_VERSION|" + Util.version); } else if (version > Util.version) { serverWindow.PrintLine("<" + GetAlias(connection) + "> attempted to connect with newer client version " + version + ". Please update the server."); TrySendMessage(connection, "ERROR|OLD_SERVER_VERSION|" + Util.version); } else TrySendMessage(connection, "OK|VERSION"); } else if (parts[0] == "ALIAS") { if (aliases.Values.Contains(parts[1])) { serverWindow.PrintLine("<" + GetAlias(connection) + "> attempted to connect with an in-use alias."); TrySendMessage(connection, "ERROR|ALIAS_IN_USE"); } else if (draftStarted && FindIndexOfDraftState(parts[1]) == -1) { serverWindow.PrintLine("<" + GetAlias(connection) + "> attempted to join an in-progress."); TrySendMessage(connection, "ERROR|DRAFT_IN_PROGRESS"); } else { // Reconnect user to draft. serverWindow.PrintLine("<" + GetAlias(connection) + "> has new alias " + parts[1] + "."); aliases.TryAdd(connection, parts[1]); TrySendMessage(connection, "OK|ALIAS"); TrySendMessage(connection, "IMAGE_DIR|" + Util.imageDirectory); TrySendMessage("USER_CONNECTED|" + parts[1]); if (draftStarted) { DraftState draftState = draftStates[FindIndexOfDraftState(parts[1])]; if (draftState.cardPool.Count > 0) TrySendMessage(connection, "CARD_POOL|" + string.Join("|", draftState.cardPool)); if (draftState.boosters.Count > 0) TrySendMessage(connection, "BOOSTER|" + string.Join("|", draftState.boosters[0])); SendPackCounts(); } else { UpdateUserList(); } } } else if (parts[0] == "PICK") { // Remove pick from pack and add to card pool. int draftIndex = FindIndexOfDraftState(aliases[connection]); DraftState draftState = draftStates[draftIndex]; DraftState nextDraftState; if (packNumber % 2 == 1) nextDraftState = draftStates[(draftIndex + 1) % draftStates.Length]; else nextDraftState = draftStates[(draftIndex + draftStates.Length - 1) % draftStates.Length]; int pickIndex = int.Parse(parts[1]); List<string> booster = draftState.boosters[0]; string pick = booster[pickIndex]; draftState.cardPool.Add(pick); booster.RemoveAt(pickIndex); draftState.boosters.Remove(booster); TrySendMessage(connection, "OK|PICK"); serverWindow.PrintLine("<" + draftState.alias + "> made a pick."); // Pass the pack to the next player, if not empty. if (booster.Count > 0) { nextDraftState.boosters.Add(booster); serverWindow.PrintLine("<" + nextDraftState.alias + "> got a new pack in their queue (now " + nextDraftState.boosters.Count + ")."); if (nextDraftState.boosters.Count == 1 && nextDraftState != draftState) TrySendMessage(nextDraftState.alias, "BOOSTER|" + string.Join("|", booster)); } else { // Check if no one has any boosters. bool packOver = true; foreach (DraftState draftStateToCheck in draftStates) if (draftStateToCheck.boosters.Count > 0) packOver = false; if (packOver) { StartNextPack(); return; } } // Current player gets the next booster in their queue, if any. if (draftState.boosters.Count > 0) { TrySendMessage(connection, "BOOSTER|" + string.Join("|", draftState.boosters[0])); } // Send message with pack count of each player. SendPackCounts(); } else if (parts[0] == "CHAT") { if (aliases.ContainsKey(connection)) { TrySendMessage("CHAT|" + GetAlias(connection) + "|" + parts[1]); serverWindow.PrintLine("<" + GetAlias(connection) + ">: " + parts[1]); } } else serverWindow.PrintLine("<" + GetAlias(connection) + "> Unknown message: " + msg); }
private void _tcpServer_OnDataAvailable(TcpServerConnection connection) { byte[] data = readStream(connection.Socket); if (data != null) { //string dataStr = Encoding.ASCII.GetString(data); try { invokeDelegate del = () => { ParseSvsData(data); }; Invoke(del); data = null; } catch { } } }
private void _tcpServer_OnConnect(TcpServerConnection connection) { _CruscottoConnected = true; }
private string GetAlias(TcpServerConnection connection) { if (aliases.ContainsKey(connection)) return aliases[connection]; return (connection.Socket.Client.RemoteEndPoint as IPEndPoint).ToString(); }
private void TrySendMessage(TcpServerConnection connection, string message) { connection.sendData(message + ";"); }
private void OnDisconnect(TcpServerConnection connection) { string alias = GetAlias(connection); string tmp; bool removed = aliases.TryRemove(connection, out tmp); serverWindow.PrintLine("<" + alias + "> disconnected."); if (removed) { TrySendMessage("USER_DISCONNECTED|" + alias); } UpdateUserList(); }
private void OnDataAvailable(TcpServerConnection connection) { byte[] data = ReadStream(connection.Socket); if (data == null) return; string dataStr = Encoding.UTF8.GetString(data); HandleMessage(connection, dataStr); }
private void OnConnect(TcpServerConnection connection) { string ipAndPort = GetAlias(connection); serverWindow.PrintLine("<" + ipAndPort + "> connected."); TrySendMessage(connection, "OK|HELLO"); }