c# - "Unable to read data from the transport connection"- C#

标签 c# .net networking

我开始涉足网络编程的世界,最近我从讲师教程中看到了一个相当古老的示例(或者有人告诉我)。

我们在大学计算机上进行了尝试,但无法正常工作,因此讲师认为这是 Windows 7 或大学计算机系统的安全设置所致。

急于找到原因,我决定在家里自己的电脑上运行相同的代码,结果没有成功。

一个解决方案中有两个项目,一个作为客户端,另一个作为服务器。一旦服务器和客户端都相互连接,客户端就会向服务器发送一个简单的字符串,该字符串会打印到控制台。在此之后,相应的连接将关闭,应用程序将正常退出。

应用程序在服务器确认它已连接到客户端时工作,但它会抛出异常(已捕获并处理)并显示以下文本:

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. - (System.IO.IOException)

现在我刚开始使用 C# 进行网络编程,我不确定去哪里找,我的讲师说他会在下周的讲座中找出问题的原因和解决方案,但我想采取一些主动行动,了解自己。

我已经添加了 Client.cs 和 Server.cs 类以防它们有用,调试器建议原因在于 Server.cs 中的第 27 行,即对 streamReader.Readline() 的调用;

注意:这绝不是家庭作业,我只是想知道为什么它不起作用。称之为学习经历 =]

客户端.cs

using System;
using System.Net.Sockets;
using System.IO;

namespace NetworkProgrammingTutorial1Client
{
    class Client
    {
        static void Main(string[] args)
        {
            TcpClient myclient;

            try
            {
                // Create a TcpClient to talk to the local host.
                myclient = new TcpClient("localhost", 1234);
            }
            catch
            {
                Console.WriteLine("Failed to connect to the server.");
                return;
            }

            // get a Network stream from the server
            NetworkStream networkStream = myclient.GetStream();
            StreamWriter streamWriter = new StreamWriter(networkStream);

            streamWriter.WriteLine("Have a message.");
            streamWriter.Flush();
        }
    }
}

Server.cs

using System;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace NetworkProgrammingTutorial1Server
{
    class Server
    {
        static void Main(string[] args)
        {
            // TcpListener is listening on the given port...                                                 {
            TcpListener tcpListener = new TcpListener(1234);
            tcpListener.Start();     
            Console.WriteLine("Server Started") ;                  
            // Accepts a new connection...
            Socket socketForClient = tcpListener.AcceptSocket();                   
            try
            {
                if (socketForClient.Connected)
                {
                    while (true)
                    {
                        Console.WriteLine("Client connected");
                        NetworkStream networkStream = new NetworkStream(socketForClient);
                        StreamReader streamReader = new StreamReader(networkStream);
                        string line = streamReader.ReadLine();
                        if (line == null)
                            break;
                        Console.WriteLine(line);
                    }
                }

                socketForClient.Close();               
                Console.WriteLine("Exiting...");
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString()) ;
            }
        }
    }
}

最佳答案

试试这个服务器代码:

TcpListener listener = new TcpListener(IPAddress.Any, 1234);
listener.Start();     

using (TcpClient client = listener.AcceptTcpClient())
using (StreamReader reader = new StreamReader(client.GetStream()))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

listener.Stop();

它在端口 1234 上监听,接受一个客户端,创建一个 StreamReader 并输出客户端发送的所有行,直到客户端关闭连接。然后它停止监听并退出。

如您所见,只创建了一个 StreamReader(并非每一行都重复创建),并且 TcpClient 和 StreamReader 都在您完成后由 using 语句处理。


您的客户端代码应该可以工作。不过,在这里也放置对象是个好主意:

using (TcpClient client = new TcpClient("localhost", 1234))
using (StreamWriter writer = new StreamWriter(client.GetStream()))
{
    writer.WriteLine("Have a message.");
    writer.Flush();

    writer.WriteLine("Have another message.");
    writer.Flush();
}

关于c# - "Unable to read data from the transport connection"- C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3807449/

相关文章:

c# - 使用反射延迟初始化对象

c# - 查询已安装 Windows 更新的准确和本地化列表

asp.net - "Could not establish trust relationship for the SSL/TLS secure channel."signalr2.2、https、.net 客户端、自定义证书异常

objective-c - OSX 的 ASIHTTP 等效项

c# - ASP.NET MVC 混合模式身份验证

c# - 不同 K 和 Volume 之间的 K-Dop 碰撞

.net - Win32_NetworkAdapterConfiguration.EnableStatic()可以用于设置多个IP地址吗?

c# - 改进正则表达式以获得 6 位数字日期 (MMDDYY)

networking - 通过 TCP/IP 获得最佳吞吐量的理想消息大小

c++ - QTcpSocket 不加载 ssl