簡體   English   中英

使用TCP偵聽器和Streamreader / writer的客戶端/服務器多線程

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

我被要求用C#編寫一個Client / Server應用程序,並且已經獲得一半完成的代碼來開始使用。

它使用ThreadPoolTcpListener以及StreamReaderStreamWriter類進行數據傳輸。客戶端具有一個固定的工作目錄。 服務器也有一個,但是可以更改。

基本上,您使用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;

                       }

出於所有應有的尊重,我認為不宜要求他人為您完成家庭作業。

作為一名學生,研究(在網絡上有任意數量的TCP套接字演示和教程)並嘗試幾種解決方案,然后再向他人尋求幫助,這是您的工作。

軟件開發既是一門藝術,又是一門科學,它需要您花時間練習藝術。 您無法通過讀書和讓別人替您工作來學習成為一名優秀的程序員。

投票關閉。

更新:不想成為一個完整的curmudgeon,下面是一些教程的鏈接,這些教程應該可以幫助您真正掌握異步TCP / socket編程:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM