locked
Socket issue RRS feed

  • Question

  • hi, i made a server client program for when ever i would be in another computer i would access mines and ask for a file if i needed it.

    the program works fine but for example, the first time i ask for a file it tells me the buffer is full( this is from the client side not the server side), the second time i ask for it i receive it just fine. another issue is that if i ask for a smaller file afterwards that file would come at the size of the previous file. And when ever i would try the client from my usb in another computer to connect to the server the files would not come full if its bigger than a few hundred kbs while when i test both server and client in my pc it receives the entire file except for the issues above. i dont know much about sockets, i made this program after looking at some examples and try to put together what ever i kinda learned from them into this. i appreciate all the help you guys can give me, thank youu


    //SERVER

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using Microsoft.Win32;
    using System.Windows.Forms;

    namespace iAccess.Server_V._2._0_
    {
        class Program
        {
            static void Main(string[] args)
            {        
                //Setup Server
                IPEndPoint ip = new IPEndPoint(IPAddress.Any, 777);
                Socket Server = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,ProtocolType.Tcp);
                Server.Blocking = true;
                Server.ReceiveBufferSize = 2000;
                Server.Bind(ip);
                Server.Listen(1);
               
                do
                {
                    //Wait for connection and write to log when connected
                    Socket Client = Server.Accept();
                    Log("");
                    Log("-Connected with: " + Client.LocalEndPoint + " At: " + DateTime.Now);
                    Log("------------------------------------------------");               

                    //Receive & Send while connected
                    while (Client.Connected)
                    {
                        try
                        {
                            //variables                   
                            string path = string.Empty;

                            //receive path from client                      
                            byte[] bytesReceived = new byte[Server.ReceiveBufferSize];
                            int bytesLenght = Client.Receive(bytesReceived);
                            path = Encoding.ASCII.GetString(bytesReceived, 0, bytesLenght);
                            Log("-Requested: " + path);

                            //check if data is a search
                            if (path.StartsWith("!"))
                            {
                                //Search for requested file
                                #region Search
                                int dot = path.IndexOf("*");
                                string DirectoryToSearch = path.Substring(1, --dot);
                                int index = dot + 2;                           
                                string fileToSearch = path.Substring(index, path.Length - index);                          

                                string searchResults = "";
                                try
                                {
                                    string[] dirs = Directory.GetDirectories("C:\\" + DirectoryToSearch);
                                    foreach (string dir in dirs)
                                    {
                                        string[] files = Directory.GetFiles(dir);
                                        foreach (string a in files)
                                        {
                                            if (a.Contains(fileToSearch))
                                            {
                                                searchResults += a + "\n";
                                            }
                                        }
                                    }
                                    if (searchResults == string.Empty)
                                    {
                                        searchResults = "Search returned no results....";
                                    }
                                    //send search results
                                    Client.Send(Encoding.ASCII.GetBytes(searchResults));
                                    Log("-Searched for: " + path);
                                }
                                catch (Exception e)
                                {
                                    Log("-The following error ocurred in performing the search: " + e.Message);
                                    Client.Send(Encoding.ASCII.GetBytes("The following error occured while trying to perform " +
                                    "the requested search.......... ERROR: " + e.Message));                               
                                }
                                #endregion                          
                            }
                            else
                            {
                                //if no search send file
                                FileStream fs = File.OpenRead(path);
                                BinaryReader br = new BinaryReader(fs);
                                byte[] bytes = br.ReadBytes(System.Convert.ToInt32(fs.Length));
                                Client.Send(bytes);
                                Log("-Requested file was sent succesfuly");
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("-The following error ocurred on the server: " + ex.Message);
                            break;
                        }
                    }
                }while (true);
            }
            //write to log function
            static void Log(string a)
            {
                if (!Directory.Exists("c://iAccess.Server(V.2.0)"))
                {
                    Directory.CreateDirectory("c://iAccess.Server(V.2.0)");
                }
                if (!File.Exists("c://iAccess.Server(V.2.0)//ServerLog.txt"))
                {
                    FileStream fss = File.Create("c://iAccess.Server(V.2.0)//ServerLog.txt");
                    fss.Close();
                }
                FileStream fs = new FileStream("c://iAccess.Server(V.2.0)//ServerLog.txt",
                    FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(a);
                sw.Close();
            }       
        }
    }

    --------------------------------------------

    //client

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;

    namespace iAccess_V._2._0_
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Get Password
                Console.Title = "iAccess Version 2.0";
                getPassword();

                //setup client
                IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("71.57.139.126"), 777);
                Socket Client = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);
                Client.ReceiveBufferSize = 200000000;

                //try to connect to server
                #region Make Connection
                bool connected = false;
                do
                {
                    try
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Connecting to iAccess.SERVER ........");
                        Client.Connect(ipEnd);
                        connected = true;
                    }
                    catch (Exception e)
                    {
                        string connect;
                        do
                        {
                            Console.Clear();
                            Console.WriteLine("Unable to connect to Server, the following error occurred");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine("Error: " + e.Message);
                            Console.WriteLine(".");
                            Console.WriteLine(".");
                            Console.WriteLine(".");
                            Console.WriteLine(". To try to make a connection enter Y or N");
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.Write("Connect again? = ");
                            connect = Console.ReadLine().ToLower();
                            if (connect == "y")
                            {
                                Console.Clear();
                                break;
                            }
                            else if (connect == "n")
                            {
                                Environment.Exit(0);
                            }
                        } while (connect != "y" || connect != "n");
                    }
                } while (!connected);
                Console.Clear();
                #endregion

                do
                {
                    //variables
                    string path = string.Empty;
                    string type = string.Empty;

                    //get path
                    menu();
                    path = Console.ReadLine();

                    //determine if requesting a search
                    if (path.ToLower() == "search")
                    {
                        #region Search
                        //variables
                        string directory;
                        string file;
                        string search;
                        string getSearch;
                       
                        //get directory to search in
                        Console.Clear();
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("search where?");
                        Console.ForegroundColor = ConsoleColor.Red;
                        directory = Console.ReadLine();

                        //get file to search for
                        Console.Clear();
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("search for what?");
                        Console.ForegroundColor = ConsoleColor.Red;
                        file = Console.ReadLine();
                        Console.Clear();
                       
                        try
                        {
                            //send search parameters to server
                            search = "!" + directory + "*" + file;
                            Client.Send(Encoding.ASCII.GetBytes(search));
                        }
                        catch (Exception e)
                        {
                            #region Display Error
                            Console.Clear();
                            Console.WriteLine("Error sending request to server, the following error ocurred");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine("Error: " + e.Message);
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(".");
                            Console.WriteLine(".");
                            Console.WriteLine(".");
                            Console.WriteLine(". This error might be due to the server going offline");
                            Console.ReadKey(true);
                            Environment.Exit(0);
                            #endregion
                        }
                        try
                        {
                            //receive search
                            byte[] receiveSearch = new byte[10000];
                            int len = Client.Receive(receiveSearch);
                            getSearch = Encoding.ASCII.GetString(receiveSearch, 0, len);                       
                            Console.WriteLine(getSearch);                      
                        }
                        catch (Exception e)
                        {
                            #region Display Error
                            Console.Clear();
                            Console.WriteLine("Error receiving search results from the server, the following error ocurred");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine("Error: " + e.Message);
                            Console.ForegroundColor = ConsoleColor.Red;                       
                            Console.ReadLine();                       
                            #endregion
                        }
                        #endregion
                    }
                    else
                    {
                        try
                        {
                            //else request file                       
                            type = Type(path);
                            Client.Send(Encoding.ASCII.GetBytes(path));
                            try
                            {
                                //receive file from server
                                #region Receive File
                                Console.Clear();
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Receiving...");

                                byte[] b = new byte[Client.ReceiveBufferSize];
                                int a = Client.Receive(b);
                                FileStream fs = new FileStream("c://Sent From(iAccess.SERVER)" + type, FileMode.Append);
                                fs.Write(b, 0, a);
                                fs.Flush();
                                fs.Close();

                                Console.Clear();
                                Console.WriteLine("Received Complete...");
                                Console.ReadKey(true);
                                Console.Clear();
                                #endregion
                            }
                            catch (Exception e)
                            {
                                #region Display Error
                                Console.Clear();
                                Console.WriteLine("Error receiving file from server, the following error ocurred");
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine("Error: " + e.Message);
                                Console.ReadKey(true);
                                Console.Clear();                          
                                #endregion
                            }
                        }
                        catch(Exception e)
                        {
                            #region Display Error
                            Console.Clear();
                            Console.WriteLine("Error Sending Request to the server, the following error ocurred");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine("Error: " + e.Message);
                            Console.ReadKey(true);
                            Console.Clear();
                            #endregion
                        }
                    }
                } while (true);
            }
            //get password function
            static void getPassword()
            {
                //variables
                const string PASSWORD = "eltimba";
                string pass;
                short counter = 3;
                bool passOk = false;

                do
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("-----------------------------------------");
                    Console.WriteLine("|| Enter Password to connect to server ||");
                    Console.WriteLine("-----------------------------------------");
                    Console.Write("Password = ");
                    Console.ForegroundColor = ConsoleColor.Red;
                    pass = Console.ReadLine();
                    if (pass != PASSWORD)
                    {
                        counter--;
                        if (counter == 0)
                            Environment.Exit(0);
                        Console.Clear();
                        Console.WriteLine("Wrong password try again...");
                        Console.WriteLine("You have " + counter + " tries left");
                        Console.ForegroundColor = ConsoleColor.Green;
                    }
                    else
                    {
                        passOk = true;
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Clear();
                    }
                } while (!passOk);
            }
            //Menu function
            static void menu()
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("-----------------------------------------");
                Console.WriteLine("|| Enter file path you want to receive ||");
                Console.WriteLine("-----------------------------------------");
                Console.Write("path = ");
                Console.ForegroundColor = ConsoleColor.Red;
            }
            //get file type function
            static string Type(string a)
            {
                string type;
                try
                {
                    int c = a.LastIndexOf(".");
                    type = a.Substring(c);
                }
                catch
                {
                    return type = ".unResolved";
                }
                return type;
            } 
        }
    }

    THANK YOU FOR YOUR TIMEE.....
    Thursday, January 15, 2009 3:00 AM

Answers

  •  It seems you've looked at bad samples. You should examine MS Asynchronous TCP/IP Socket Client and Asynchronous TCP/IP Socket Server. You need to define a StateObject that will contain buffer. You will tap the buffer as soon it is full and the next batch of your file will come in overlapping the data you've retrieved. There are complete code samples at the links. You can adjust them to your app and they will work.
    AlexB
    • Marked as answer by salserito6780 Friday, January 16, 2009 2:37 AM
    Thursday, January 15, 2009 4:19 AM

All replies

  •  It seems you've looked at bad samples. You should examine MS Asynchronous TCP/IP Socket Client and Asynchronous TCP/IP Socket Server. You need to define a StateObject that will contain buffer. You will tap the buffer as soon it is full and the next batch of your file will come in overlapping the data you've retrieved. There are complete code samples at the links. You can adjust them to your app and they will work.
    AlexB
    • Marked as answer by salserito6780 Friday, January 16, 2009 2:37 AM
    Thursday, January 15, 2009 4:19 AM
  • thanks i'll look at the examples
    Friday, January 16, 2009 2:37 AM