0

I've been asked to write a Client / Server application in C#, and have been given half-completed code to get started.

It uses the ThreadPool, and TcpListener with StreamReader and StreamWriter classes for data transfer.The client has a working directory, which is fixed. The server has one too, but can change.

Basically, you type in an option on the client using a switch statement, and the server processes that option and sends it back to the client.

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

namespace Client
{
/// <summary>
/// Remote File Service client
/// </summary>
class Client
{
    /// <summary>
    /// Static entry point to client code
    /// </summary>
    /// <param name="args">unused</param>
    static void Main(string[] args)
    {
        string dir = @"c:\st12_13d1_files";

        try
        {
            Directory.SetCurrentDirectory(dir);
        }
        catch (DirectoryNotFoundException e)
        {
            Console.WriteLine("The specified directory does not exist. {0}", e);
        }

        try
        {
            using (TcpClient client = new TcpClient("localhost", 50012))
            using (NetworkStream stream = client.GetStream())
            using (StreamReader reader = new StreamReader(stream))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.AutoFlush = true;
                string option;

                do
                {
                    Console.WriteLine("-Menu-\n");

                    Console.WriteLine("1-Print out file names-\n");
                    Console.WriteLine("2-Current Working Directory-\n");
                    Console.WriteLine("3-Files Present on the Server-\n");
                    Console.WriteLine("4- List of Subdirectory Names-\n");
                    Console.WriteLine("5- Change Server Directory Location-\n");
                    Console.WriteLine("6-Copy the contents of a file specified-\n");
                    Console.WriteLine("7-Close-\n");

                    Console.WriteLine("Please enter your choice: ");

                    option = Console.ReadLine();

                    switch (option)
                    {
                        case "1":
                        case "one":

                        Console.WriteLine("You have selected Print out file names: ");

                        break;
                    } 

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;
using System.Security.Cryptography;

namespace Server
{
/// <summary>
/// Remote File Service main functionality
/// </summary>
public class ServerMainline
{
    public ServerMainline()
    {
        /*
        * *** TO DO - your code goes here ***
        * record initial current working directory value in a global variable
        */

        string serv = (@"..\..");        

        try
        {
            //Set the current directory.
            Directory.SetCurrentDirectory(serv);
        }
        catch (DirectoryNotFoundException e)
        {
            Console.WriteLine("The specified directory does not exist. {0}", e);
        }

        TcpListener server = null;
        try
        {
            ThreadPool.SetMaxThreads(50, 50);

            server = new TcpListener(IPAddress.Any, 50012);
            server.Start();

            while (true)
            {

                Console.WriteLine("Waiting for a new Client...");
                TcpClient client = server.AcceptTcpClient();

                ThreadPool.QueueUserWorkItem(serviceClient, client);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Server mainline: SocketException: {0}", e);
        }
        finally
        {
            server.Stop();
            server.Server.Close();
        }
    }

    /// <summary>
    /// method to run to handle each client on separate thread
    /// </summary>
    void serviceClient(object clientObject)
    {
        Thread currentThread = Thread.CurrentThread;
        int threadID = currentThread.GetHashCode();    

        try
        {
            using (TcpClient client = (TcpClient)clientObject)
            using (NetworkStream stream = client.GetStream())
            using (StreamReader reader = new StreamReader(stream))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.AutoFlush = true;
                Console.WriteLine("Connected with a client, threadID: {0}", threadID);

                string option = reader.ReadLine();

                while (option != "7")

                switch (option)
                {
                 case "1":
                 case "one":

                 string[] myfiles = Directory.GetFiles(@"c:\st12_13d1_files");
                 Console.WriteLine("File Names {0}",Directory.GetFiles
                 (@"c:\st12_13d1_files"));
                        foreach (string file in myfiles)
                        {
                          //Console.WriteLine(file);
                          Console.WriteLine(Path.GetFileName(file));
                          writer.WriteLine(myfiles);
                        }

                        break;

                       }
Field Day
  • 9
  • 2
  • 2
  • 2
    Are you new to C# or just network programming? Do you have a textbook? – Ryan Frame Mar 26 '13 at 15:36
  • Yes; Provide code! :) – Rudi Visser Mar 26 '13 at 15:40
  • 1
    I'm not sure this is a question. Could you clarify what you are looking for? – Jake H Mar 26 '13 at 15:40
  • Too bad `what have you tried` comments are no longer accepted :-( Voting to close as too localized in this case. – Darin Dimitrov Mar 26 '13 at 15:43
  • I'm basically in University, could you tell?! I studied C# and basic Object Oriented stuff back in September, but this semester, it's all about Threads and Sockets. I've got C# 4.0 in a Nutshell, but it doesn't really answer my question. Seems I can't provide code for another 8 hours - I've just joined Stack Overflow. If any willing, kind person fancies helping by email? I'd be forever in your debt! – Field Day Mar 26 '13 at 16:06
  • any applicable code should be part of the question. However it should be as short as possible to still be relevant. Don't expect people to analyze whole projects for you, that should be your job. Since you're in university, isn't the point that you learn new things? "I don't understand this, halp!!!" doesn't sound like the best attitude. – Tar Mar 26 '13 at 16:15
  • I appreciate what you're saying, Tar. However this comments box is limited to how many characters you can enter. I understand certain things, but 90% of the people in my year are stuck with this. I'm not asking anyone to do my entire coursework for me, however I'm fairly new to C# in general, and I'm just hoping for a little help. – Field Day Mar 26 '13 at 16:20
  • What I'm stuck with, is how to get the Server to pass data back to the Client, upon entering an option number in the Client menu. I can get everything to work in the Client, but not from Server to Client. For example: CLIENT: case "1": Console.WriteLine("You have selected Print out file names: "); SERVER: case "1": string[] myfiles = Directory.GetFiles(@"c:\st12_13d1_files"); Console.WriteLine("File Names: {0}", Directory.GetFiles(@"c:\st12_13d1_files")); foreach (string file in myfiles) { Console.WriteLine(Path.GetFileName(file)); writer.WriteLine(myfiles); } – Field Day Mar 26 '13 at 16:25
  • In both Client and Server, I'm using: using (TcpClient client = new TcpClient("localhost", 50012)) using (NetworkStream stream = client.GetStream()) using (StreamReader reader = new StreamReader(stream)) using (StreamWriter writer = new StreamWriter(stream)) – Field Day Mar 26 '13 at 16:31
  • @FieldDay: @Tar was saying to edit your question to add the code, not to post it in the comments. And unless the client is sending "1" to the server, the server's `switch` statement is incorrect. Have you asked your professor for help? – Ryan Frame Mar 26 '13 at 16:55
  • @RyanFrame thanks for replying man. I've edited my code to display a selection of the CLient and Server code. If I can figure out how to implement this first option, case 1, I can do the rest. Hope you can help! – Field Day Mar 26 '13 at 17:12
  • ok, so now that you posted the code, it's time you said what it does and doesn't do. It looks pretty much ok to me, except you need to add "writer.WriteLine(option);" in the client. Then if it still doesn't work, you might need to set NoDelay/autoflush or whatever the options are on all the streams/sockets objects. – Tar Mar 26 '13 at 20:26

1 Answers1

3

With all due respect, I don't think it's appropriate to ask others to complete your homework assignments for you.

As a student, it should be your job to research (there are any number of TCP socket demos and tutorials on the web) and experiment with several solutions before resorting to asking others for help.

Software development is as much art as it is science and it requires that you spend time practicing your art. You cannot learn to be a great programmer by reading books and having others do your work for you.

Voting to close.

Update: Not wanting to be a complete curmudgeon, here are some links to some tutorials that should help you really get to grips with async TCP/socket programming:

Community
  • 1
  • 1
Rich Turner
  • 10,800
  • 1
  • 51
  • 68
  • 1
    I respect that. I'll research TCP socket demos as you've mentioned, despite having already done so. I've already experimented with various solutions to try to get this to work, to no avail. I'll also remember the help you've given me. Thanks Richard. – Field Day Mar 26 '13 at 17:33
  • Thanks for taking my feedback on-board. I (somehow) still remember my (pre-internet) days as a student and can only imagine the temptation that sties like StackOverflow present, helping you reduce the delay between completing homework and getting to the bar/gym ;) I've added some links to a related question in my answer above that should provide you a good methodical approach to writing async TCP/socket code. – Rich Turner Mar 26 '13 at 19:45
  • Thanks again Richard. Being the grand old age of 29, I'm past looking for quick answers so I can hit the bar. I'm a bit of a latecomer to network programming, but have been trying everything for 5 days solid to get this to work. I appreciate the links you provided though, I'll check those out. – Field Day Mar 26 '13 at 23:50