简体   繁体   English

尝试从网络流中读取时,C#代码挂起

[英]C# Code hangs when trying to read from Network stream

I already tried lots of possible solutions, different types of writing and reading to stream and all that. 我已经尝试了很多可能的解决方案,不同类型的读写流以及所有这些。 But I cant seem to get my code to work. 但是我似乎无法使我的代码正常工作。

I basically want to simply send a message to localhost:25565 and then read the message back from localhost:25565 with Console.WriteLine(); 我基本上只想简单地将一条消息发送到localhost:25565,然后使用Console.WriteLine()从localhost:25565读回该消息;

  public void Connect(String server, String message)
    {
        Int32 port = 25565;
        string localhost = "127.0.0.1";
        IPAddress localAdd = IPAddress.Parse(localhost);
        TcpListener listener = new TcpListener(localAdd, port);
        Console.WriteLine("listening...");
        listener.Start();
        try
        {
            TcpClient client = new TcpClient(server, port);
            client.NoDelay = true;
            NetworkStream stream = client.GetStream();


            if (stream.CanWrite)
             {
                Console.WriteLine("You can write to this NetworkStream.");


                StreamWriter writer = new StreamWriter(client.GetStream());
                writer.Write(message);
                writer.Flush();

            }
             else
             {
                 Console.WriteLine("Sorry.  You cannot write to this NetworkStream.");
             }

             Console.WriteLine("Sent: {0}", message);

             String responseData = String.Empty;

             Console.WriteLine("InBetween test");

             if(stream.CanRead)
             {
                Console.WriteLine("You can read this stream");

                StreamReader reader = new StreamReader(stream);
                string recievedData = reader.ReadToEnd();
                Console.WriteLine(recievedData);

             }
             else
             {
                 Console.WriteLine("Sorry.  You cannot read from this NetworkStream.");
             }

            Console.WriteLine("All completed test");


           stream.Close();
           client.Close();
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: {0}", e);
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }

        Console.WriteLine("\n Press Enter to continue...");
        Console.Read();
    }

This is what appears when I debug my app. 这是我调试应用程序时出现的内容。 https://gyazo.com/95464cc4201c98ccd04cac004b0ea540 https://gyazo.com/95464cc4201c98ccd04cac004b0ea540

It stops after You can read this stream . 您可以阅读此流后,它停止。

Thank you in advance for your help. 预先感谢您的帮助。

You are missing the Accept call on the listening server socket. 您在侦听服务器套接字上缺少“接受”呼叫。

Below is your example modified to work. 以下是修改后的示例,可以正常工作。 The server part is run in a background thread now, so the server and the client can run in parallel. 服务器部分现在在后台线程中运行,因此服务器和客户端可以并行运行。

public class Program
{
    public static readonly int Port = 25565;    
    public static readonly string Localhost = "127.0.0.1";
    public static readonly string Host = "127.0.0.1";

    public static void RunServer()
    {
        // start the server
        IPAddress localAdd = IPAddress.Parse(Localhost);
        TcpListener listener = new TcpListener(localAdd, Port);
        listener.Start();
        Console.WriteLine($"Server: Listening on {localAdd}:{Port}");
        // TODO proper exit from server
        while (true)
        {
            // accept client socket -- note that we handle only one connection at a time
            Socket cliSoc = listener.AcceptSocketAsync().Result;
            Console.WriteLine($"Server: Client socket accepted, from {cliSoc.LocalEndPoint}");
            while (true)
            {
                if (!cliSoc.Connected)
                    break;
                int bufLen = 1000;
                byte[] buf = new byte[bufLen];
                int read = cliSoc.Receive(buf);
                if (read == 0)
                    break;
                string msg = System.Text.Encoding.ASCII.GetString(buf, 0, read);
                Console.WriteLine($"Server: Read from socket: {read} '{msg}'");

                string response = "OK";
                byte[] responseArr = System.Text.Encoding.ASCII.GetBytes(response.ToCharArray());
                int sent = cliSoc.Send(responseArr);
                Console.WriteLine($"Server: sent response ({sent} bytes)");

                cliSoc.Shutdown(SocketShutdown.Both);
            }
            Console.WriteLine($"Server: Client socket closed");
        }
    }

    public static void Connect(string message)
    {
        Task.Run(() => RunServer());

        try
        {
            TcpClient client = new TcpClient();
            client.ConnectAsync(Host, Port).Wait();
            client.NoDelay = true;
            NetworkStream stream = client.GetStream();

            if (stream.CanWrite)
            {
                Console.WriteLine("Client: You can write to this NetworkStream.");

                StreamWriter writer = new StreamWriter(stream);
                writer.Write(message);
                writer.Flush();
                Console.WriteLine($"Client: Wrote to stream ({message}).");
            }
            else
            {
                Console.WriteLine("Client: Sorry.  You cannot write to this NetworkStream.");
            }

            String responseData = String.Empty;

            Console.WriteLine("Client: Reading");

            if(stream.CanRead)
            {
                Console.WriteLine("Client: You can read this stream");

                StreamReader reader = new StreamReader(stream);
                string recievedData = reader.ReadToEnd();
                Console.WriteLine($"Client: Read: {recievedData}");

            }
            else
            {
                Console.WriteLine("Client: Sorry.  You cannot read from this NetworkStream.");
            }

            Console.WriteLine("Client: All completed test");


            stream.Flush();
            //client.Close();
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: {0}", e);
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }

        Console.WriteLine("\n Press Enter to continue...");
        Console.Read();
    }

    public static void Main(string[] args)
    {
        Connect("Hi there!");
    }

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

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