Exception: Acess Violation in client C#
<p>I am trying to learn C# through trials and errors. I have a server in Python, and the client in C#.</p>

<p>The client is supposed to get data from the server, save it to disk ((which it doesn't)), then continue using that data to communicate until the user decides to exit it.</p>

<p>Unfortunately, it has been raising an Exception Access Violation for quite some time, and provides no helpful information as to why.</p>

<p>Code: </p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Scripting.Hosting;
using System.Threading;
using Rage;
using System.Net.Sockets;
using System.IO;

[assembly: Rage.Attributes.Plugin("LSPDFROnlineClient", Description = "LSPDFR Online Client. Used to connect to LSPDFR Online.", Author = "Thecheater887")]

namespace LSPDFROnlineClient
{

    public class EntryPoint
    {
        private static int IsDead;

        public static void Main()
        {
            IsDead = 0;
            Thread mt = new Thread(new ThreadStart(Run));
            mt.Start();
            while (true)
            {
                if (IsDead == 1)
                {
                    break;
                }
                GameFiber.Yield();
            }
            return;
        }
        public static void Run()
        {
            File.WriteAllText("C:/ProgramData/dbg.log","1");
            try
            {
                Byte[] header;
                Byte[] packet;
                Byte[] data;
                Byte[] kad;
                Byte[] td;
                int paylen;
                String rd;
                String nd;
                String msgid;

                File.WriteAllText("C:/ProgramData/dbg.log", "2");

                TcpClient connector = new TcpClient();
                connector.Connect("127.0.0.1", 5773);
                NetworkStream conn = connector.GetStream();
                try {
                    File.WriteAllText("C:/ProgramData/dbg.log", "3");
                    FileStream savedat = File.OpenRead("C:/Users/Public/Documents/save.dat");
                    BinaryReader savdat = new BinaryReader(savedat);
                    nd = savdat.ReadString();
                    savdat.Close();
                    if (nd.Length == 16)
                    {

                    } else {
                        File.WriteAllText("C:/ProgramData/save.dat", "user000000000000");
                        nd = "user000000000000";
                    }
                }
                catch
                {
                    File.WriteAllText("C:/ProgramData/save.dat", "user000000000000");
                    nd = "user000000000000";
                }
                File.WriteAllText("C:/ProgramData/dbg.log", "4");
                data = new Byte[26];
                data = Encoding.ASCII.GetBytes("clogr00000" + nd);
                conn.Write(data, 0, data.Length);

                while (true)
                {
                    try
                    {
                        // Get header of packet
                        header = new Byte[26];
                        Int32 rcvhead = conn.Read(header, 0, header.Length);
                        String hd = Encoding.ASCII.GetString(header, 0, rcvhead);
                        //Deal with it 8-)
                        msgid = hd.Substring(0, 5);
                        paylen = Convert.ToInt32(hd.Substring(5, 5));
                        string servkey = hd.Substring(10, 16);
                    }
                    catch
                    {
                        continue;
                    }
                    File.WriteAllText("C:/ProgramData/dbg.log", "5");
                    try
                    {
                        //Receive packet data
                        if (paylen &gt; 0)
                        {
                            packet = new Byte[paylen];
                            Int32 newdata = conn.Read(packet, 0, packet.Length);
                            rd = Encoding.ASCII.GetString(packet, 0, newdata);
                        }
                        else
                        {
                            rd = null;
                        }
                        File.WriteAllText("C:/ProgramData/dbg.log", "6");
                        if (msgid == "ConOK")
                        {
                            File.WriteAllText("C:/ProgramData/dbg.log", "7");
                            string userid = rd.Substring(0, 16);
                            Game.DisplayHelp(rd.Substring(16, (rd.Length - 16)));
                            File.WriteAllText("C:/ProgramData/save.dat", userid);
                            File.WriteAllText("C:/ProgramData/dbg.log", "8");
                        }
                        else if (msgid == "savdt")
                        {
                            File.WriteAllText("C:/ProgramData/dbg.log", "9");
                            string[] tnd = rd.Split(',');
                            var nud = new List&lt;string&gt;();
                            nud.Add("Player1");
                            nud.AddRange(tnd);
                            File.WriteAllText("C:/ProgramData/dbg.log", "A");
                            string name = nud[0];
                            string streetname = nud[1];
                            int money = Convert.ToInt32(nud[2]);
                            int bounty = Convert.ToInt32(nud[3]);
                            int playerrep = Convert.ToInt32(nud[4]);
                            File.WriteAllText("C:/ProgramData/dbg.log", "B");
                            int rep = Convert.ToInt32(nud[5]);
                            string pclass = nud[6];
                            bool canbecop = Convert.ToBoolean(nud[7]);
                            int rank = Convert.ToInt32(nud[8]);
                            int stars = Convert.ToInt32(nud[9]);
                            int cites = Convert.ToInt32(nud[10]);
                            File.WriteAllText("C:/ProgramData/dbg.log", "C");
                            int citesgiven = Convert.ToInt32(nud[11]);
                            int citesdismissed = Convert.ToInt32(nud[12]);
                            int arrestsmade = Convert.ToInt32(nud[13]);
                            int arrested = Convert.ToInt32(nud[14]);
                            int convictionsmade = Convert.ToInt32(nud[15]);
                            int convitced = Convert.ToInt32(nud[16]);
                            string warrant = nud[17];
                            File.WriteAllText("C:/ProgramData/dbg.log", "D");
                            int prisontimeremaining = Convert.ToInt32(nud[18]);
                            int copskilled = Convert.ToInt32(nud[19]);
                            int crimskilled = Convert.ToInt32(nud[20]);
                            int civskilled = Convert.ToInt32(nud[21]);
                            int bountyclaimed = Convert.ToInt32(nud[22]);
                            int overflowprep = Convert.ToInt32(nud[23]);
                            string title = nud[24];
                            bool banned = Convert.ToBoolean(nud[25]);
                            bool vip = Convert.ToBoolean(nud[26]);
                            int viprank = Convert.ToInt32(nud[27]);
                            File.WriteAllText("C:/ProgramData/dbg.log", "E");

                            var v3 = new Vector3();
                            float posx = Convert.ToSingle(nud[29]);
                            float posy = Convert.ToSingle(nud[30]);
                            float posz = Convert.ToSingle(nud[31]);
                            v3.X = posx;
                            v3.Y = posy;
                            v3.Z = posz;

                            File.WriteAllText("C:/ProgramData/dbg.log", "EE");
                            int rot = Convert.ToInt32(nud[32]);
                            File.WriteAllText("C:/ProgramData/dbg.log", "FF");

                            World.TeleportLocalPlayer(v3, false);
                            File.WriteAllText("C:/ProgramData/dbg.log", "F");
                            string custommessage = nud[28];
                            if (custommessage == "null")
                            {

                            } else {
                                Game.DisplayNotification(custommessage);
                            }
                        }
                        else if (msgid == "isalv")
                        {
                            kad = new Byte[26];
                            kad = Encoding.ASCII.GetBytes("yesil00000" + nd);
                            conn.Write(kad, 0, kad.Length);
                        }
                        else if (msgid == "pospk")
                        {

                        }
                        else
                        {
                            Game.DisplayNotification("Unknown packet recieved! ID: " + msgid);
                        }
                        //send end client turn
                        td = new Byte[26];
                        td = Encoding.ASCII.GetBytes("endmt00000" + nd);
                        conn.Write(td, 0,td.Length);
                        File.WriteAllText("C:/ProgramData/dbg.log", "0");
                        //
                    }
                    catch (Exception e)
                    {
                        Game.DisplayHelp(Convert.ToString(e));
                        Game.DisplayNotification("LSPDFR Online has crashed. Try reloading it maybe..?");
                    }
                }
            } catch (Exception e) {
                Game.DisplayHelp(Convert.ToString(e));
                Game.DisplayNotification("Connection interrupted! Reconnecting....");
                IsDead = 1;
                return;
            }
        }
    }
}
</code></pre>

<p>The protocol goes as such;</p>

<pre><code>Client -&gt; Server: LoginRequest
Server -&gt; Client: LoginOkay
Client -&gt; Server: EndTurnMessage
Server -&gt; Client: SaveDataMessage
Client -&gt; Server: EndTurnMessage
Server -&gt; Client: PositionUpdatePacket
Client -&gt; Server: EndTurnMessage
</code></pre>

<p>Then continue routine, however, the server only receives one of these <code>EndTurnMessage</code> packets, which means it is choking on the save data portion, right?</p>

<p>Possibly, but that was working at an earlier time without flaw, and hasn't been modified since.</p>

<p>It is a class file, so it can't be debugged, and I've been tearing my hair out as to what is causing it.</p>

<p>Yes, it is crap-code, and needs rewritten at some point, I am aware, but I'd like it to work before I rewrite it entirely.</p>

<p>TL;DR: Why is this code raising an Access Violation? It's around the <code>savdt</code> sector or after.</p>

<p><strong>UPDATE:</strong> I fixed the issue posted in the first answer, however, that didn't do much, so, as posted in both the answer and comments, it's rather difficult to debug with a program, so I'll try the old fashioned route of logging info every so many lines of code. I'll keep this updated.</p>

<p><strong>UPDATE 2:</strong> I have figured out from the log debugging, that the line causing the error is <code>World.TeleportLocalPlayer(v3, false);</code>. Unfortunatley, <code>World</code> can't be inherited, and the documentation claims that <code>Vector3</code> requires you to set it's internal values using get and set. I saw that on MSDN previously, but have no clue about how to search it, and there is nor <code>get</code> or <code>set</code> methods available within that <code>Vector3</code> object.</p>

<p>You might have a stream that remained open, which prevents a new one to be created. If the msgid is "ConOK" you are creating a new instance without closing it after the write operation is done.</p>

<pre><code>if (msgid == "ConOK"){
    string userid = rd.Substring(0, 16);
    Game.DisplayHelp(rd.Substring(16, (rd.Length - 16)));
    FileStream savedat = File.OpenWrite(("C:/ProgramData/save.dat"));
    BinaryWriter savdat = new BinaryWriter(savedat);
    savdat.Write(userid);
    // Close file stream here
 }
</code></pre>

<p>But that's just a first guess. You can help us and yourself by making use of the debugger. The fact that your code is contained by a "class file" is no problem but a requirement. </p>

<p>Hava a look at this article for more information about debugging in the world of C#:
<a href="http://www.dotnetperls.com/debugging" rel="nofollow">http://www.dotnetperls.com/debugging</a></p>

c# python networking visual-studio-2015