简体   繁体   English

使用TCP侦听器和Streamreader / writer的客户端/服务器多线程

[英]Client / Server multi threaded using TCP Listener and Streamreader / writer

I've been asked to write a Client / Server application in C#, and have been given half-completed code to get started. 我被要求用C#编写一个Client / Server应用程序,并且已经获得一半完成的代码来开始使用。

It uses the ThreadPool , and TcpListener with StreamReader and StreamWriter classes for data transfer.The client has a working directory, which is fixed. 它使用ThreadPoolTcpListener以及StreamReaderStreamWriter类进行数据传输。客户端具有一个固定的工作目录。 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. 基本上,您使用switch语句在客户端上输入一个选项,然后服务器处理该选项并将其发送回客户端。

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;

                       }

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. 作为一名学生,研究(在网络上有任意数量的TCP套接字演示和教程)并尝试几种解决方案,然后再向他人寻求帮助,这是您的工作。

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: 更新:不想成为一个完整的curmudgeon,下面是一些教程的链接,这些教程应该可以帮助您真正掌握异步TCP / socket编程:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM