【问题标题】:Client / Server multi threaded using TCP Listener and Streamreader / writer客户端/服务器多线程使用 TCP Listener 和 Streamreader/writer
【发布时间】:2015-03-11 00:33:25
【问题描述】:

我被要求用 C# 编写一个客户端/服务器应用程序,并且已经完成了一半的代码来开始。

它使用ThreadPoolTcpListenerStreamReaderStreamWriter类进行数据传输。客户端有一个工作目录,它是固定的。服务器也有一个,但可以更改。

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

                       }

【问题讨论】:

  • 您是 C# 新手还是网络编程新手?你有课本吗?
  • 是的;提供代码! :)
  • 我不确定这是一个问题。你能澄清一下你在找什么吗?
  • 太糟糕了what have you tried cmets 不再被接受 :-( 在这种情况下投票结束,因为过于本地化。
  • 我基本上在大学,你能告诉我吗?!我在九月份学习了 C# 和基本的面向对象的东西,但是这个学期,它都是关于线程和套接字的。简而言之,我有 C# 4.0,但它并没有真正回答我的问题。似乎我不能再提供 8 小时的代码 - 我刚刚加入 Stack Overflow。如果任何愿意,善良的人想通过电子邮件提供帮助?我会永远欠你的债!

标签: c# tcplistener


【解决方案1】:

恕我直言,我认为让其他人为你完成家庭作业是不合适的。

作为一名学生,您的工作应该是研究(网络上有任意数量的 TCP 套接字演示和教程)并尝试多种解决方案,然后再向他人寻求帮助。

软件开发既是一门艺术,也是一门科学,它要求您花时间练习自己的艺术。你不能通过阅读书籍和让其他人为你工作来学习成为一名优秀的程序员。

投票结束。

更新:不想成为一个完全的脾气暴躁的人,这里有一些教程的链接,它们应该可以帮助您真正掌握异步 TCP/socket 编程:

【讨论】:

  • 我尊重这一点。正如您所提到的,我将研究 TCP 套接字演示,尽管已经这样做了。我已经尝试了各种解决方案来尝试使其正常工作,但无济于事。我也会记住你给我的帮助。谢谢理查德。
  • 感谢您接受我的反馈。我(不知何故)仍然记得我作为学生的(上网前)日子,只能想象像 StackOverflow 这样的网站存在的诱惑,帮助你减少完成作业和去酒吧/健身房之间的延迟;)我添加了一些链接到我上面的答案中的一个相关问题,它应该为您提供一种编写异步 TCP/socket 代码的好方法。
  • 再次感谢理查德。作为 29 岁的高龄,我不再寻找快速的答案,这样我就可以达到标准了。我在网络编程方面有点迟到,但我已经尝试了 5 天的所有努力以使其正常工作。我很感谢您提供的链接,我会检查一下。
猜你喜欢
  • 2014-05-05
  • 2016-09-26
  • 2019-04-18
  • 2014-03-04
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
相关资源
最近更新 更多