7 Replies - 853 Views - Last Post: 05 December 2016 - 02:57 PM Rate Topic: -----

#1 CoolCell6   User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 20-November 16

Trying to figure out how to Disconnect and reconnect a Rcon Socket

Posted 03 December 2016 - 05:05 PM

I found a dll clase for steam rcon and converting it to a windows form application. Everything works but I can't figure out how to disconnect the rcon connection then start another connection without errors?

I added: (but get a error and can not reconnect
public void  Disconnect_RCONConnection()
        {

            S.Shutdown(SocketShutdown.Both);

        }


Here's the DLL Class File: Grcon.cs
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections;

namespace LibGRcon
{
 
    public class Grcon
    {
        public Grcon()
        {
            S = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            PacketCount = 0;

#if DEBUG
            TempPackets = new ArrayList();
#endif
        }


        public void  Disconnect_RCONConnection()
        {

            S.Shutdown(SocketShutdown.Both);

        }

        public bool Connect(IPEndPoint Server, string password)
        {
            try
            {
                S.Connect(Server);
            }
            catch (SocketException)
            {
                onerror(ConnectionFailedString);
                OnConnectionSuccess(false);
                return false;
            }

            RCONPacket SA = new RCONPacket();
            SA.RequestId = 1;
            SA.String1 = password;
            SA.ServerDataSent = RCONPacket.SERVERDATA_sent.SERVERDATA_AUTH;

            SendRCONPacket(SA);

            // This is the first time we've sent, so we can start listening now!
            StartGetNewPacket();

            return true;
        }

      

       
        public void ServerCommand(string command)
        {
            if (connected)
            {
                RCONPacket PacketToSend = new RCONPacket();
                PacketToSend.RequestId = 2;
                PacketToSend.ServerDataSent = RCONPacket.SERVERDATA_sent.SERVERDATA_EXECCOMMAND;
                PacketToSend.String1 = command;
                SendRCONPacket(PacketToSend);
            }
        }

        void SendRCONPacket(RCONPacket p)
        {
            byte[] Packet = p.OutputAsBytes();
            S.BeginSend(Packet, 0, Packet.Length, SocketFlags.None, new AsyncCallback(SendCallback), this);
        }

        bool connected;
        public bool Connected
        {
            get { return connected; }
        }

        void SendCallback(IAsyncResult ar)
        {
            S.EndSend(ar);
        }

        int PacketCount;

        void StartGetNewPacket()
        {
            RecState state = new RecState();
            state.IsPacketLength = true;
            state.Data = new byte[4];
            state.PacketCount = PacketCount;
            PacketCount++;
#if DEBUG
            TempPackets.Add(state);
#endif
            S.BeginReceive(state.Data, 0, 4, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
        }

#if DEBUG
        public ArrayList TempPackets;
#endif

        void ReceiveCallback(IAsyncResult ar)
        {
            bool recsuccess = false;
            RecState state = null;

            try
            {
                int bytesgotten = S.EndReceive(ar);
                state = (RecState)ar.AsyncState;
                state.BytesSoFar += bytesgotten;
                recsuccess = true;

#if DEBUG
                Console.WriteLine("Receive Callback. Packet: {0} First packet: {1}, Bytes so far: {2}", state.PacketCount, state.IsPacketLength, state.BytesSoFar);
#endif

            }
            catch (SocketException)
            {
                onerror(ConnectionClosed);
            }

            if (recsuccess)
                ProcessIncomingData(state);
        }

        void ProcessIncomingData(RecState state)
        {
            if (state.IsPacketLength)
            {
                // First 4 bytes of a new packet.
                state.PacketLength = BitConverter.ToInt32(state.Data, 0);

                state.IsPacketLength = false;
                state.BytesSoFar = 0;
                state.Data = new byte[state.PacketLength];
                S.BeginReceive(state.Data, 0, state.PacketLength, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
            }
            else
            {
                // Do something with data...

                if (state.BytesSoFar < state.PacketLength)
                {
                    // Missing data.
                    S.BeginReceive(state.Data, state.BytesSoFar, state.PacketLength - state.BytesSoFar, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
                }
                else
                {
                    // Process data.
#if DEBUG
                    Console.WriteLine("Complete packet.");
#endif

                    RCONPacket RetPack = new RCONPacket();
                    RetPack.ParseFromBytes(state.Data, this);

                    ProcessResponse(RetPack);

                    // Wait for new packet.
                    StartGetNewPacket();
                }
            }
        }

        void ProcessResponse(RCONPacket P)
        {
            switch (P.ServerDataReceived)
            {
                case RCONPacket.SERVERDATA_rec.SERVERDATA_AUTH_RESPONSE:
                    if (P.RequestId != -1)
                    {
                        // Connected.
                        connected = true;
                        onerror(ConnectionSuccessString);
                        OnConnectionSuccess(true);
                    }
                    else
                    {
                        // Failed!
                        onerror(ConnectionFailedString);
                        OnConnectionSuccess(false);
                    }
                    break;
                case RCONPacket.SERVERDATA_rec.SERVERDATA_RESPONSE_VALUE:
                    if (hadjunkpacket)
                    {
                        // Real packet!
                        OnServerOutput(P.String1);
                    }
                    else
                    {
                        hadjunkpacket = true;
                        onerror(GotJunkPacket);
                    }
                    break;
                default:
                    onerror(UnknownResponseType);
                    break;
            }
        }

        bool hadjunkpacket;

        internal void OnServerOutput(string output)
        {
            if (ServerOutput != null)
            {
                ServerOutput(output);
            }
        }

        internal void onerror(string error)
        {
            if (Errors != null)
            {
                Errors(error);
            }
        }

        internal void OnConnectionSuccess(bool info)
        {
            if (ConnectionSuccess != null)
            {
                ConnectionSuccess(info);
            }
        }

        public event StringOutput ServerOutput;
        public event StringOutput Errors;
        public event BoolInfo ConnectionSuccess;

        string ResponseOverride = null;
            
                         


        public static string ConnectionClosed = "[CONNECTIONCLOSEDBYREMOTEHOST]";
        public static string ConnectionSuccessString = "[CONNECTIONSUCCEEDED]";
        public static string ConnectionFailedString = "[CONNECTIONFAILED]";
        public static string UnknownResponseType = "[UNKNOWNRESPONSE]";
        public static string GotJunkPacket = "[JUNKPACKET]";

        Socket S;
    }

    public delegate void StringOutput(string output);
    public delegate void BoolInfo(bool info);

    internal class RecState
    {
        internal RecState()
        {
            PacketLength = -1;
            BytesSoFar = 0;
            IsPacketLength = false;
        }

        public int PacketCount;
        public int PacketLength;
        public int BytesSoFar;
        public bool IsPacketLength;
        public byte[] Data;
    }



    internal class RCONPacket
    {
        internal RCONPacket()
        {
            RequestId = 0;
            String1 = "[JUNKPACKET]";
            String2 = String.Empty;
            ServerDataSent = SERVERDATA_sent.None;
            ServerDataReceived = SERVERDATA_rec.None;
        }

        internal byte[] OutputAsBytes()
        {
            byte[] packetsize;
            byte[] reqid;
            byte[] serverdata;
            byte[] bstring1;
            byte[] bstring2;

            UTF8Encoding utf = new UTF8Encoding();

            bstring1 = utf.GetBytes(String1);
            bstring2 = utf.GetBytes(String2);

            serverdata = BitConverter.GetBytes((int)ServerDataSent);
            reqid = BitConverter.GetBytes(RequestId);

            // Compose into one packet.
            byte[] FinalPacket = new byte[4 + 4 + 4 + bstring1.Length + 1 + bstring2.Length + 1];
            packetsize = BitConverter.GetBytes(FinalPacket.Length - 4);

            int BPtr = 0;
            packetsize.CopyTo(FinalPacket, BPtr);
            BPtr += 4;

            reqid.CopyTo(FinalPacket, BPtr);
            BPtr += 4;

            serverdata.CopyTo(FinalPacket, BPtr);
            BPtr += 4;

            bstring1.CopyTo(FinalPacket, BPtr);
            BPtr += bstring1.Length;

            FinalPacket[BPtr] = (byte)0;
            BPtr++;

            bstring2.CopyTo(FinalPacket, BPtr);
            BPtr += bstring2.Length;

            FinalPacket[BPtr] = (byte)0;
            BPtr++;

            return FinalPacket;
        }

        internal void ParseFromBytes(byte[] bytes, Grcon parent)
        {
            int BPtr = 0;
            ArrayList stringcache;
            UTF8Encoding utf = new UTF8Encoding();

            // First 4 bytes are ReqId.
            RequestId = BitConverter.ToInt32(bytes, BPtr);
            BPtr += 4;
            // Next 4 are server data.
            ServerDataReceived = (SERVERDATA_rec)BitConverter.ToInt32(bytes, BPtr);
            BPtr += 4;
            // string1 till /0
            stringcache = new ArrayList();
            while (bytes[BPtr] != 0)
            {
                stringcache.Add(bytes[BPtr]);
                BPtr++;
            }
            String1 = utf.GetString((byte[])stringcache.ToArray(typeof(byte)));
            BPtr++;

            // string2 till /0

            stringcache = new ArrayList();
            while (bytes[BPtr] != 0)
            {
                stringcache.Add(bytes[BPtr]);
                BPtr++;
            }
            String2 = utf.GetString((byte[])stringcache.ToArray(typeof(byte)));
            BPtr++;

            // Repeat if there's more data?

            if (BPtr != bytes.Length)
            {
                parent.onerror("[JUNKPACKET]");
            }
        }

        public enum SERVERDATA_sent : int
        {
            SERVERDATA_AUTH = 3,
            SERVERDATA_EXECCOMMAND = 2,
            None = 255
        }

        public enum SERVERDATA_rec : int
        {
            SERVERDATA_RESPONSE_VALUE = 0,
            SERVERDATA_AUTH_RESPONSE = 2,
            None = 255
        }


       


        internal int RequestId;
        internal string String1;
        internal string String2;
        internal RCONPacket.SERVERDATA_sent ServerDataSent;
        internal RCONPacket.SERVERDATA_rec ServerDataReceived;
    }
}


Here's a image of the error I get:

Posted Image

This post has been edited by Skydiver: 03 December 2016 - 05:34 PM
Reason for edit:: Put code in code tags. Learn how to do this yourself.


Is This A Good Question/Topic? 0
  • +

Replies To: Trying to figure out how to Disconnect and reconnect a Rcon Socket

#2 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7462
  • View blog
  • Posts: 25,113
  • Joined: 05-May 12

Re: Trying to figure out how to Disconnect and reconnect a Rcon Socket

Posted 03 December 2016 - 05:36 PM

How did the original code disconnect and reconnect? It should not be any different between console or GUI.

Also since this is brand new code, why use ancient end of life WinForms? Use WPF or Xamarin that has a path forward.
Was This Post Helpful? 0
  • +
  • -

#3 CoolCell6   User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 20-November 16

Re: Trying to figure out how to Disconnect and reconnect a Rcon Socket

Posted 03 December 2016 - 05:41 PM

The original code disconnect and reconnect via close and opening the console app it had no command to disconnect and reconnect to another rcon connection.

This is the original Console app Program.cs
using System;
using System.Net;
using System.Threading;


namespace SourceRcon
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
            string ipaddress, password, command;
            int port;

            bool interactive;

            if (args.Length > 0)
            {
                if (args.Length == 4)
                {
                    interactive = false;
                    ipaddress = args[0];
                    port = int.Parse(args[1]);
                    password = args[2];
                    command = args[3];
                }

                else
                {
                    Console.WriteLine("To use in interactive mode, use no parameters.");
                    Console.WriteLine("Else use parameters in the form: ip port password command");
                    Console.WriteLine("Enclose the command in \" marks if it is more than one word");
                    Console.WriteLine("E.g. sourcercon 192.168.0.5 27015 testpass \"say Testing!\"");
                    return;
                }
            }
            else
            {
                interactive = true;
                Console.WriteLine("Enter IP Address:");
                ipaddress = Console.ReadLine();
                Console.WriteLine("Enter port:");
                port = int.Parse(Console.ReadLine());
                Console.WriteLine("Enter password:");
                password = Console.ReadLine();
                command = null;
            }

			SourceRcon Sr = new SourceRcon();
			Sr.Errors += new StringOutput(ErrorOutput);
			Sr.ServerOutput += new StringOutput(ConsoleOutput);

            if (Sr.Connect(new IPEndPoint(IPAddress.Parse(ipaddress), port), password))
			{
				while(!Sr.Connected)
				{
					Thread.Sleep(10);
				}
                if(interactive)
                {
                    Console.WriteLine("Ready for commands:");
				    while(true)
				    {
				    	Sr.ServerCommand(Console.ReadLine());
				    }
                }
                else
                {
                    Sr.ServerCommand(command);
                    Thread.Sleep(1000);
                    return;
                }
			}
			else
			{
				Console.WriteLine("No connection!");
				Thread.Sleep(1000);
			}
		}

		static void ErrorOutput(string input)
		{
			Console.WriteLine("Error: {0}", input);
		}

		static void ConsoleOutput(string input)
		{
			Console.WriteLine("Console: {0}", input);
		}

	}


This post has been edited by Skydiver: 03 December 2016 - 05:48 PM
Reason for edit:: Put code in code tags. Learn how to do this yourself.

Was This Post Helpful? 0
  • +
  • -

#4 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7462
  • View blog
  • Posts: 25,113
  • Joined: 05-May 12

Re: Trying to figure out how to Disconnect and reconnect a Rcon Socket

Posted 03 December 2016 - 05:53 PM

Dude. Learn how to use code tags!

So why not just follow suit? Just close the GUI? Consider that the Windows recommended UI is SDI: single document interface. The idea is when you are done interacting with a "document", you simply close it and the app terminates.

If you really want to keep the app alive, then why not create a new instance of the connector. Why recycle the old one?
Was This Post Helpful? 0
  • +
  • -

#5 CoolCell6   User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 20-November 16

Re: Trying to figure out how to Disconnect and reconnect a Rcon Socket

Posted 03 December 2016 - 06:08 PM

Sorry to waist your time DUDE! I'm Learning I'll find another forum that's not so critical to learners!
Was This Post Helpful? 0
  • +
  • -

#6 astonecipher   User is offline

  • Enterprise Software Architect
  • member icon

Reputation: 3151
  • View blog
  • Posts: 11,956
  • Joined: 03-December 12

Re: Trying to figure out how to Disconnect and reconnect a Rcon Socket

Posted 03 December 2016 - 10:58 PM

Funny how a question is critical. I hear Stack Overflow is really friendly.
Was This Post Helpful? 0
  • +
  • -

#7 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7462
  • View blog
  • Posts: 25,113
  • Joined: 05-May 12

Re: Trying to figure out how to Disconnect and reconnect a Rcon Socket

Posted 04 December 2016 - 07:56 AM

I suspect that the OP is just offended that it was pointed out that he didn't read the instructions right in the edit box to use code tags. Two posts, so the instructions were shown twice.

That or he just doesn't like my use of "dude". He may have read it as "Dude, roll down the window before hurling!" instead of "Dude, mind the gap!".
Was This Post Helpful? 0
  • +
  • -

#8 CoolCell6   User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 20-November 16

Re: Trying to figure out how to Disconnect and reconnect a Rcon Socket

Posted 05 December 2016 - 02:57 PM

Guys I must apologize for my wording and behavior! I honestly don't even remember posting any of this I did find my rcon project on my laptop. I guess my wife let me use my lap top in the hospital I was drugged up on morphine had emergency appendix removal surgery. I even had to call my best friend for texting him crap when I was doped up. Told my wife no more laptop or cell phone if they put morphine in me again. Still finding crazy crap post I didn't know I did.

string Mymsg = "Sorry!";


My wife said I got touchy about everything even when the doctor said the surgery went well I got pissed at the doctor.


My honest apologizes!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1