Jump to content

  • Log In with Google      Sign In   
  • Create Account

Xanather

Member Since 24 Apr 2012
Offline Last Active Nov 05 2014 12:01 AM

#5082667 Learning C# and Xna for game programming

Posted by Xanather on 02 August 2013 - 10:40 PM

Be sure to take a look at MonoGame. XNA wont be updated anymore but MonoGame will continue on.




#5081706 UDP protocol to minimize latency?

Posted by Xanather on 30 July 2013 - 08:14 AM

Just want to put this out there, I am developing a client-server 2D TCP networked game, I tried connecting to my game server (hosted at my home) on my laptop though my phones WiFi hotspot (I was further out in the country at the time aswell). That version's build had liquid animation that was compressed -> It ended up running pretty well and latency was within 200ms and this is a game that is not developed for internet through the phone.

 

It would be pointless to use UDP if your going to just reimplement TCP. If some packets can be dropped and/or you want a custom error detection design other than the way TCP handles it then UDP would make more sense, otherwise in my opinion TCP saves time and is optimized well.




#5080453 Looking for the right framework/sdk/game engine

Posted by Xanather on 25 July 2013 - 08:18 AM

MonoGame is actually continuing on, whether XNA continues on or not. Several new features that are in MonoGame include RenderTarget3D, multiple window support, and some others. MonoGame can basically build to all the platforms you want with high code re-usability. I am using a varient of MonoGame called MonoGameSDL and it is working very well so far. MonoGameSDL uses SDL2 as a backend but still follows the XNA layout.

 

Not sure about MonoGameSDL's performance compared to say a native openGL/directX program though, but then you have to ask what would be better, productivity or performance?

 

I have been able to draw thousands of sprites per frame using MonoGame.

Edit: talking about desktop here, MonoGame does support iOS, Android and WindowsPhone8.




#5057653 Microsoft burned down my home, where now?

Posted by Xanather on 28 April 2013 - 11:39 PM

I agree, I think it would have been a great idea for Microsoft to continue with XNA and integrate it with the new Windows 8 Metro/store etc, instead they did not, who knows why?

 

I think the final determination of Microsoft and indie game developers will be what they do with the NextBox. Ive already left XNA and have been using MonoGame and MonoGame only (I only use XNA to compile content once in a while). The Windows DirectX platform of MonoGame will probably release soon (the current released windows version uses OpenGL), you can already use a early version of it by downloading from the MonoGame github.

 

The DirectX MonoGame platform uses SharpDX and Direct3D11, they have already started expanding the API further than XNA (multiple window support, RenderTarget3D class, etc...)




#5057195 Improve on Java or preapre for C++?

Posted by Xanather on 27 April 2013 - 04:34 AM

Managed languages like C#/Java have to convert MSIL/Java Bytecode (which is what C#/Java compilers create) into machine code at runtime. This can slow down the initial startup up of the application (using something like NGEN can overcome this though). Not only that but both languages use a garbage collector to pick up and delete unused objects as well - which also uses process time.

 

C++ does not do this and is always compiled to machine code before use. No garbage collector exists in C++. C++ is just lower-level in general compared to C#/Java and allows you to deal with smaller things for specific optimizations.

 

You don't have to learn both at the SAME time, if you think your going good with Java then keep using it. I'm just saying there's nothing wrong with learning both :)




#5056326 What should a games programmer know?

Posted by Xanather on 24 April 2013 - 04:30 AM

You aren't really taught how to do "specific algorithms" because all algorithms will be different based on the context. You just end up "self-learning" how to create algorithms - something that comes with just doing general programming.

 

I think XNA would be a good choice, it is very high level and you will also familiarize yourself more with the visual studio IDE. MonoGame is getting better, I recommend using that aswell.




#5055437 Switching from Java to C#

Posted by Xanather on 21 April 2013 - 02:34 AM

Well, you'll need to learn the base class library obviously. I don't know Java that much but from memory I remember:

 

- All method names have a capital as their first letter.

- New: properies
- No checked exceptions

 

take a look at this for feature comparison: http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java




#5053828 [SharpDX.Toolkit] How to store game assets

Posted by Xanather on 16 April 2013 - 07:40 AM

XNB's do infact speed up the loading time, think of it as being converted to a raw read-ready file that can be sent straight into memory. I don't think it will matter with what your doing with SharpDX anyway.

 

MonoGame is good, and they are actually breaking away from the XNA framework now and adding new things like RenderTarget3D and multiple window support. I recommend taking a look at it :)




#5053638 [SharpDX.Toolkit] How to store game assets

Posted by Xanather on 15 April 2013 - 05:47 PM

Well yeah that shouldnt be a problem, unless you dont want users to look through files that easy. Most of the time though the raw assets end up being extracted from compiled files.

 

I use XNA/MonoGame which uses .xnb files, which can be decompiled.




#5053474 [SharpDX.Toolkit] How to store game assets

Posted by Xanather on 15 April 2013 - 09:59 AM

I would just place the content files in a seperate folder in the Project, prefarably under the name of "Content". You then selected all the content that you place in there and choose "Copy if newer".

 

Everytime you compile the project the content is copied to the debug/release directory accordingly.




#5043311 C# for 2D game

Posted by Xanather on 15 March 2013 - 03:29 AM

So why choose monogame, if XNA won't be updated?

MonoGame will be (and already has) started to introduce some new features beyond XNA. MonoGame is not tied to XNA anymore since just about full 1:1 code compatibility has pretty much been reached.

 

 

Now installed monoGame, and created project, and seeing that xna is included. So it use XNA libs?

MonoGame currently still uses the Microsoft.Xna.Framework namespaces, this will probably change in the future. The main reason why its like this is so people can port their XNA games over to MonoGame with less hassle. This means MonoGame does not use the XNA libraries at all.

 

 

Tried to give my friend realeased project, but only gets error.

MonoGame does have some dependancies depending on the platform, but like I said does not require XNA to be installed.
From what I know:
The current released windows platform, which uses OpenGL for rendering, also uses OpenAL, you can google OpenAL that and tell your friend to install that (OpenAL is actually installed when you install MonoGame 3.1. There should be no other dependencies needed. Once the windows directX platform is released the only required dependency that will need to be installed is .net 4.0/4.5.

 

 

Or maybe u have to suggest other C# game dev solution?

I think MonoGame would be a good choice, you could also use XNA, no problem with that even if its not going to be updated anymore (you can swap XNA -> MonoGame code bases easily anyway).

 

The only problem with MonoGame at the moment is that the content pipeline is still missing (I think it will be available soon though).




#5043281 C#/XNA socket programming question

Posted by Xanather on 15 March 2013 - 01:49 AM

From past experience I don't think there is a easy way to getting actual keyboard char presses from the keyboard. Last time I successfully achieved it on XNA I had to use unmanaged code (PInvoke) etc... However, the Keyboard.GetState() is fast enough if you call it at the beginning of each tick/update since its as fast as the game is simulating.

 

Anyway I'm guessing your question is how to make two sprites move on the screen, 1 sprite per player? Your server will need a list to store all clients that connect, you will also need to remember the IP for each client as a way as separating up different clients (or you could just use TCP which I think would be easier for beginning networking).

Then you need to do all these required things:
- Handle disbatching of new client connections (add them to the list), which then means...

- Once a client connects you need to send data to all other currently connected clients to indicate that someone has connected (so the existing clients can add the new player to their list aswell).

- Handle the disconnections/time outs of connections, and do the same as the point above, but to remove clients from lists.

- Handle receiving messages, and then relaying the messages to all connected clients.




#5031729 Please vote to support request for DirectX tools for C#

Posted by Xanather on 13 February 2013 - 02:45 AM

I am definately voting for this. This would be awesome, since XNA is apparently being discontinued it seems like microsoft is doing nothing when working with C# and DirectX together.




#5030273 Game development on: Linux or Windows

Posted by Xanather on 08 February 2013 - 09:26 PM

If your going to use something like C# you should look at MonoGame. You would be able to develop your game on Linux and very easily port it over to windows (In most circumstances I think MonoGame has over 95% code compatibility).




#5020250 Quality of my code

Posted by Xanather on 11 January 2013 - 04:03 AM

I haven't done much network programming lately so I decided to make a small program. I quickly made this small program within 2 days, it uses .net's TcpClient and TcpListener classes.

 

All the program does is transfer files to/from computers. Server mode of the program accepts files, while client mode of the program sends files.

 

I would like any experienced (networking) programmers to tell me what I should improve on.

 

Looking at the code now I would:

 

1. try and somehow make reading the file and uploading the file happen on different threads (which will probably make the transfer faster). Same with downloading/saving the file.

 

2. split the code up a bit mode, its mostly crammed into one method - how would I do this though?

 

Here are the 4 classes used in the program:

 

Program.cs...

//By xanather.
using System;

namespace Transfar
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Transfar - Clean and Fast TCP File Transfers";
            Console.WriteLine("Loaded: Transfar v1.0");
            if (args.Length == 0)
            {
                ConsoleColor color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("This executable needs to be passed some arguments...");
                Console.ForegroundColor = color;
                ShowHelp();
                Console.Write("Press any key to close this program... ");
                Console.ReadKey();
                return;
            }
            else
            {
                if (args[0] == "-server")
                {
                    Server server;
                    server = new Server();
                    server.Start(args);
                }
                else if (args[0] == "-client")
                {
                    Client client;
                    client = new Client();
                    client.Start(args);
                }
                else
                {
                    ConsoleColor color = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("Invalid argument(s). Here is the list of arguments...");
                    Console.ForegroundColor = color;
                    ShowHelp();
                    Console.Write("Press any key to close this program... ");
                    Console.ReadKey();
                    return;
                }
            }
        }
        static void ShowHelp()
        {
            Console.WriteLine("Available arguments (commands) for this application:");
            Console.WriteLine("Argument\t\tDescription");
            Console.WriteLine("-server [dir] [port]\n");
            Console.WriteLine("\t\t\tStarts the application in server mode so the");
            Console.WriteLine("\t\t\tapplication can receive and download files sent by");
            Console.WriteLine("\t\t\tTransfar clients. Port forwarding on the router");
            Console.WriteLine("\t\t\tmay be required so that the server can listen for");
            Console.WriteLine("\t\t\tinternet connections.\n");
            Console.WriteLine("\t\t\tThe [dir] argument specifies the folder/directory");
            Console.WriteLine("\t\t\tthe server should place received/downloaded files");
            Console.WriteLine("\t\t\tfrom clients. This argument is required.\n");
            Console.WriteLine("\t\t\tThe [port] argument specifies the port in which the");
            Console.WriteLine("\t\t\tserver should listen to for accepting Transfer client");
            Console.WriteLine("\t\t\tconnections. Default port is 5655. This argument is");
            Console.WriteLine("\t\t\toptional.\n");
            Console.WriteLine("-client [address] [file] [port]\n");
            Console.WriteLine("\t\t\tStarts the application in client mode so the");
            Console.WriteLine("\t\t\tapplication can send and upload files to a Transfar");
            Console.WriteLine("\t\t\tserver.\n");
            Console.WriteLine("\t\t\tThe [address] argument specifies the server's IP");
            Console.WriteLine("\t\t\tin which to connect to. This argument is required.\n");
            Console.WriteLine("\t\t\tThe [file] argument specifies the file on disk");
            Console.WriteLine("\t\t\tthe client should send/upload to the server.");
            Console.WriteLine("\t\t\tThis argument is required.\n");
            Console.WriteLine("\t\t\tThe [port] argument specifies which port the client");
            Console.WriteLine("\t\t\tshould use to connect to Transfar servers of the same");
            Console.WriteLine("\t\t\tport. Default port is 5655. This argument is optional.\n");
        }
    }
}

ArrayHelper.cs...

//By xanather
using System;

namespace Transfar
{
    static class ArrayHelper
    {
        public static bool Equals(byte[] a, byte[] b)
        {
            if (a.Length != b.Length)
            {
                return false;
            }
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] != b[i])
                {
                    return false;
                }
            }
            return true;
        }
    }
}

Client.cs...

//By xanather
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

namespace Transfar
{
    class Client
    {
        public static readonly byte[] clientVerify = new byte[] { 6, 2, 5, 1, 255 };
        public string srcFile;
        public int port;
        public string address;
        public void Start(string[] args)
        {
            //get address argument
            if (args.Length > 1)
            {
                address = args[1];
            }
            else
            {
                ConsoleColor color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("No IP address has been entered.");
                Console.WriteLine("It is a required argument.");
                Console.ForegroundColor = color;
                Console.Write("Press any key to close this program... ");
                Console.ReadKey();
                return;
            }
            //get file argument
            if (args.Length > 2)
            {
                if (File.Exists(args[2]))
                {
                    srcFile = args[2];
                }
                else
                {
                    ConsoleColor color = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("The file specified does not exist.");
                    Console.WriteLine("It is a required argument.");
                    Console.ForegroundColor = color;
                    Console.Write("Press any key to close this program... ");
                    Console.ReadKey();
                    return;
                }
            }
            else
            {
                ConsoleColor color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("No file location has been entered.");
                Console.WriteLine("It is a required argument.");
                Console.ForegroundColor = color;
                Console.Write("Press any key to close this program... ");
                Console.ReadKey();
                return;
            }
            if (args.Length > 3)
            {
                try
                {
                    port = int.Parse(args[3]);
                    if (port < 0 || port > 65565)
                    {
                        throw new FormatException();
                    }
                }
                catch (FormatException)
                {
                    ConsoleColor color = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("Invalid port argument...");
                    Console.ForegroundColor = color;
                    Console.Write("Press any key to close this program... ");
                    Console.ReadKey();
                    return;
                }
            }
            else
            {
                port = Server.defaultPort;
            }
            //check the size of the file
            try
            {
                long fileSize = checked(new FileInfo(srcFile).Length);
            }
            catch (OverflowException)
            {
                ConsoleColor color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("The file is too big! The maximum size supported is " + long.MaxValue + " bytes.");
                Console.ForegroundColor = color;
                Console.Write("Press any key to close this program... ");
                Console.ReadKey();
                return;
            }
            ProcessConnection();
        }
        public void ProcessConnection()
        {
            TcpClient client;
            NetworkStream stream;
            try
            {
                Console.WriteLine("Attempting to connect...");
                client = new TcpClient(address, port);
                stream = client.GetStream();
            }
            catch (SocketException e)
            {
                ConsoleColor color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Cannot connect to server.");
                Console.WriteLine(e.Message);
                Console.ForegroundColor = color;
                Console.Write("Press any key to close this program... ");
                Console.ReadKey();
                return;
            }
            Console.WriteLine("Connected to server.");
            int readSize;
            int readAmount;
            byte[] readBuffer;
            int readAmountTotal;
            byte[] writeBuffer;
            byte[] writeBuffer1;
            //send client verification
            stream.Write(clientVerify, 0, clientVerify.Length);
            //read server verification
            readAmount = Server.serverVerify.Length;
            readBuffer = new byte[readAmount];
            readAmountTotal = readAmount;
            while (readAmount != 0)
            {
                readSize = stream.Read(readBuffer, readAmountTotal - readAmount, readAmount);
                readAmount -= readSize;
            }
            if (!ArrayHelper.Equals(readBuffer, Server.serverVerify))
            {
                stream.Close();
                client.Close();
                ConsoleColor color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Disconnected, invalid server.");
                Console.ForegroundColor = color;
                Console.Write("Press any key to close this program... ");
                Console.ReadKey();
                return;
            }
            //write file name
            string fileName = Path.GetFileName(srcFile);
            writeBuffer1 = Encoding.UTF8.GetBytes(fileName);
            writeBuffer = new byte[writeBuffer1.Length + 1];
            writeBuffer[0] = (byte)writeBuffer1.Length;
            Buffer.BlockCopy(writeBuffer1, 0, writeBuffer, 1, writeBuffer1.Length);
            stream.Write(writeBuffer, 0, writeBuffer.Length);
            //read if file already exists in server directory
            stream.Read(readBuffer, 0, 1);
            if (readBuffer[0] == 0)
            {
                stream.Close();
                client.Close();
                ConsoleColor color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Disconnected, the file {0} already exists in the server directory.");
                Console.ForegroundColor = color;
                Console.Write("Press any key to close this program... ");
                Console.ReadKey();
                return;
            }
            //write the size (in bytes) of the file
            Console.WriteLine("Now uploading the file...");
            long fileSize = new FileInfo(srcFile).Length;
            stream.Write(BitConverter.GetBytes(fileSize), 0, 8);
            //start uploading the whole file
            long writeRemaining = fileSize;
            int percent = 0;
            int prevPercent = -1;
            using (FileStream fileStream = new FileStream(srcFile, FileMode.Open))
            {
                while (writeRemaining != 0)
                {
                    readAmount = short.MaxValue; //write 65565 chuncks.
                    if (readAmount > writeRemaining)
                    {
                        readAmount = (int)writeRemaining;
                    }
                    readBuffer = new byte[readAmount];
                    fileStream.Read(readBuffer, 0, readAmount);
                    try
                    {
                        stream.Write(readBuffer, 0, readAmount);
                    }
                    catch (IOException e)
                    {
                        stream.Close();
                        client.Close();
                        ConsoleColor color = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("Disconnected: " + e.Message);
                        Console.ForegroundColor = color;
                        Console.Write("Press any key to close this program... ");
                        Console.ReadKey();
                        return;
                    }
                    writeRemaining -= readAmount;
                    percent = (int)(((fileSize - writeRemaining) / (double)fileSize * 100));
                    if (percent != prevPercent)
                    {
                        prevPercent = percent;
                        Console.WriteLine("{0} - Upload at {1}%. {2}KB remaining ({3}KB/{4}KB).", fileName, percent, writeRemaining / 1024, (fileSize - writeRemaining) / 1024, fileSize / 1024);
                    }
                }
            }
            //write clientVerify for final handshake
            stream.Write(clientVerify, 0, clientVerify.Length);
            stream.Close();
            client.Close();
            Console.WriteLine("Upload complete!");
            Console.Write("Press any key to close this program... ");
            Console.ReadKey();
        }
    }
}

Server.cs...

//By xanather
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

namespace Transfar
{
    class Server
    {
        public static readonly byte[] serverVerify = new byte[]{10, 10, 35, 244, 21};
        public const int defaultPort = 5655;
        public int port;
        public string destDirectory;
        public AutoResetEvent connectionSignal = new AutoResetEvent(false);
        public TcpListener listener;
        public void Start(string[] args)
        {
            //get directory argument
            if (args.Length > 1)
            {
                if (!args[1].EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    args[1] += Path.DirectorySeparatorChar;
                }
                if (Directory.Exists(args[1]))
                {
                    destDirectory = args[1];
                }
                else
                {
                    ConsoleColor color = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("The directory specified does not exist.");
                    Console.WriteLine("It is a required argument.");
                    Console.ForegroundColor = color;
                    Console.Write("Press any key to close this program... ");
                    Console.ReadKey();
                    return;
                }
            }
            else
            {
                ConsoleColor color = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("No destination directory has been entered.");
                Console.WriteLine("It is a required argument.");
                Console.ForegroundColor = color;
                Console.Write("Press any key to close this program... ");
                Console.ReadKey();
                return;
            }
            //get port argument
            if (args.Length > 2)
            {
                try
                {
                    port = int.Parse(args[2]);
                    if (port < 0 || port > 65565)
                    {
                        throw new FormatException();
                    }
                }
                catch (FormatException)
                {
                    ConsoleColor color = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("Invalid port argument...");
                    Console.ForegroundColor = color;
                    Console.Write("Press any key to close this program... ");
                    Console.ReadKey();
                    return;
                }
            }
            else
            {
                port = defaultPort;
            }
            StartListening();
        }
        public void StartListening()
        {
            listener = new TcpListener(IPAddress.Any, port);
            listener.Start();
            while (true)
            {
                Console.WriteLine("Listening for connections...");
                ProcessClientAsync();
                connectionSignal.WaitOne();
                connectionSignal.Reset();
            }
        }
        public async void ProcessClientAsync()
        {
            TcpClient client = await listener.AcceptTcpClientAsync();
            NetworkStream stream = client.GetStream();
            connectionSignal.Set();
            //connection variables
            string socketAddress = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
            int socketPort = int.Parse(((IPEndPoint)client.Client.RemoteEndPoint).Port.ToString());
            int readSize;
            int readAmount;
            byte[] readBuffer;
            int readAmountTotal;
            //verify client connection
            readAmount = Client.clientVerify.Length;
            readBuffer = new byte[readAmount];
            readAmountTotal = readAmount;
            while (readAmount != 0)
            {
                readSize = stream.Read(readBuffer, readAmountTotal - readAmount, readAmount);
                readAmount -= readSize;
            }
            if (!ArrayHelper.Equals(readBuffer, Client.clientVerify))
            {
                stream.Close();
                client.Close();
                Console.WriteLine(string.Format("[{0}:{1}] Warning: Invalid connection request by this IP.", socketAddress, socketPort));
                return;
            }
            //send server verification
            stream.Write(serverVerify, 0, serverVerify.Length);
            Console.WriteLine(string.Format("[{0}:{1}] Connected.", socketAddress, socketPort));
            //read file name
            stream.Read(readBuffer, 0, 1);
            readAmount = readBuffer[0];
            readBuffer = new byte[readAmount];
            readAmountTotal = readAmount;
            while (readAmount != 0)
            {
                readSize = stream.Read(readBuffer, readAmountTotal - readAmount, readAmount);
                readAmount -= readSize;
            }
            string fileName = Encoding.UTF8.GetString(readBuffer);
            //write if file already exists in destDirectory
            if (File.Exists(destDirectory + fileName))
            {
                stream.Write(new byte[] { 0 }, 0, 1);
                stream.Close();
                client.Close();
                Console.WriteLine(string.Format("[{0}:{1}] Disconnected, tried to save a existing file ({2}).", socketAddress, socketPort, fileName));
                return;
            }
            else
            {
                stream.Write(new byte[] { 1 }, 0, 1);
            }
            //read the size (in bytes) of the file
            readAmount = 8;
            readBuffer = new byte[readAmount];
            readAmountTotal = readAmount;
            while (readAmount != 0)
            {
                readSize = stream.Read(readBuffer, readAmountTotal - readAmount, readAmount);
                readAmount -= readSize;
            }
            long fileSize = BitConverter.ToInt64(readBuffer, 0);
            //start downloading the whole file
            long readRemaining = fileSize;
            int percent = 0;
            int prevPercent = -1;
            Console.WriteLine(string.Format("[{0}:{1}] Now downloading file {2}. Total size: {3}KB.", socketAddress, socketPort, fileName, fileSize / 1024));
            using (FileStream fileStream = new FileStream(destDirectory + fileName, FileMode.CreateNew))
            {
                while (readRemaining != 0)
                {
                    readAmount = short.MaxValue; //read 65565 chuncks.
                    if (readAmount > readRemaining)
                    {
                        readAmount = (int)readRemaining;
                    }
                    readBuffer = new byte[readAmount];
                    readAmountTotal = readAmount;
                    while (readAmount != 0)
                    {
                        try
                        {
                            readSize = stream.Read(readBuffer, readAmountTotal - readAmount, readAmount);
                        }
                        catch (IOException e)
                        {
                            stream.Close();
                            client.Close();
                            Console.WriteLine(string.Format("[{0}:{1}] Disconnected: {2}", socketAddress, socketPort, e.Message));
                            Console.WriteLine(string.Format("[{0}:{1}] The file has not been received in full and may be corrupted.", socketAddress, socketPort, e.Message));
                            return;
                        }
                        readAmount -= readSize;
                    }
                    fileStream.Write(readBuffer, 0, readAmountTotal);
                    readRemaining -= readAmountTotal;
                    percent = (int)(((fileSize - readRemaining) / (double)fileSize) * 100);
                    if (percent != prevPercent)
                    {
                        prevPercent = percent;
                        Console.WriteLine("[{0}:{1}] {2} - Download at {3}%. {4}KB remaining ({5}KB/{6}KB).", socketAddress, socketPort, fileName, percent, readRemaining / 1024, (fileSize - readRemaining) / 1024, fileSize / 1024);
                    }
                }
            }
            //read clientVerify for final handshake
            readAmount = Client.clientVerify.Length;
            readBuffer = new byte[readAmount];
            readAmountTotal = readAmount;
            while (readAmount != 0)
            {
                readSize = stream.Read(readBuffer, readAmountTotal - readAmount, readAmount);
                readAmount -= readSize;
            }
            if (!ArrayHelper.Equals(readBuffer, Client.clientVerify))
            {
                stream.Close();
                client.Close();
                Console.WriteLine(string.Format("[{0}:{1}] Warning: Unspecified error, file may not be received properly.", socketAddress, socketPort));
                return;
            }
            else
            {
                Console.WriteLine(string.Format("[{0}:{1}] {2} - Download complete!", socketAddress, socketPort, fileName));
            }
            stream.Close();
            client.Close();
        }
    }
}

Ok, that ended up longer than I thought.

 

All replies are appriciated.

Thanks,

Xanather.






PARTNERS