public void Disconnect() { if (con != null && isConnected) { con.Close(); } //con.CommandRecieved existingUsers = new Dictionary <string, User>(); existingChannels = new Dictionary <string, ExistingChannel>(); joinedChannels = new Dictionary <string, Channel>(); battle = null; battleID = 0; username = ""; isLoggedIn = false; isConnected = false; isChanScanning = false; }
private static void DataRecieveCallback(IAsyncResult res) { ServerConnection server = (ServerConnection)res.AsyncState; try { server.readPosition += server.stream.EndRead(res); // actual data read - this blocks } catch { // there was error while reading - stream is broken server.Close(); return; } // check data for new line - isolating commands from it for (int i = server.readPosition - 1; i >= 0; --i) { if (server.readBuffer[i] == '\n') { // new line found - convert to string and parse commands String recData = Encoding.ASCII.GetString(server.readBuffer, 0, i + 1); // convert recieved bytes to string // cycle through lines of data foreach (string line in recData.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)) { // for each line = command do string[] args = line.Split(' '); // split arguments /*for (int j = 0; j < args.Length; ++j) { // replace \t with ' ' in every argument * args[j] = args[j].Replace('\t', ' '); * }*/ // prepare and send command recieved info ServerConnectionEventArgs command = new ServerConnectionEventArgs(); command.ServerConnection = server; command.RequestId = server.commandNumber++; command.Command = args[0]; command.Result = ServerConnectionEventArgs.ResultTypes.Success; command.Parameters = new string[args.Length - 1]; for (int j = 1; j < args.Length; ++j) { command.Parameters[j - 1] = args[j]; } if (server.CommandRecieved != null) { server.CommandRecieved(server, command); } } // copy remaining data (not ended by \n yet) to the beginning of buffer for (int x = 0; x < server.readPosition - i - 1; ++x) { server.readBuffer[x] = server.readBuffer[x + i + 1]; } server.readPosition = server.readPosition - i - 1; break; } } // prepare to read more data int rembuf = server.readBuffer.Length - server.readPosition; if (rembuf <= 0) { // read buffer too small, increase it byte[] n = new byte[server.readBuffer.Length * 2]; server.readBuffer.CopyTo(n, 0); server.readBuffer = n; rembuf = server.readBuffer.Length - server.readPosition; } try { server.stream.BeginRead(server.readBuffer, server.readPosition, rembuf, new AsyncCallback(DataRecieveCallback), server); } catch { // there was error while reading - stream is broken server.Close(); return; } }