C# 网络问题

标签 c# networking tcp networkstream

我正在尝试创建一个程序,允许用户将他们编写的某些第三方代码的 JAR 文件上传到在线服务器,然后接收返回的字符串消息作为响应。

在线服务器使用带有标准 TCP 套接字网络的 Java 编码。客户端使用了一个额外的软件,这意味着我必须使用 C# 作为文件 uploader 。我写的代码包含在下面。在此程序中,文件 uploader 工作正常,但由于某种原因,客户端在到达 input.ReadLine() 时挂起,它应该从服务器接收 String 消息响应。

public static string sendFile(string filepath) {

    String response = "";

    // Get the file
    Stream fileStream = File.OpenRead(filepath);

    byte[] buffer = new byte[fileStream.Length];
    fileStream.Read(buffer, 0, buffer.Length);

    try {

        // Create the connection
        TCPClient client = new TCPClient("127.0.0.1", 21000);

        NetworkStream stream = client.GetStream();

        // Send the file to the server
        stream.Write(buffer, 0, buffer.Length);
        stream.Flush();

        // Receive a single string response from the server
        if (stream.CanRead) {

            StreamReader input = new StreamReader(stream);
            inputString = input.ReadLine();

        }

        input.Close();
        stream.Close();
        client.Close();

    }

    catch (IOException e) {

        print ("Error: " + e);

    }

    // Return the response message string
    return inputString;

}

我也曾尝试使用 StreamWriter 实现上述代码,而不是直接从 NetworkStream 本身写入。不幸的是,StreamWriter 类没有发送字节数组的方法(只有一个字符数组)。我想知道问题是否是由我直接调用 NetworkStream 的 Write 方法而不是使用 StreamWriter 引起的。

如果有人知道为什么上面的代码不起作用,请告诉我。或者,如果您有不同的解决方案,允许我使用相同的 TCPClient 连接发送文件(字节数组)并接收回字符串消息,那么也请随时提及。

问候,

米达维。

最佳答案

readline 挂起是因为它只有在成功从服务器读取一行后才会返回,这是使用阻塞套接字的缺点。请确保您的服务器正确发送一行(以“\n”结尾的字符串

关于C# 网络问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8912055/

相关文章:

c# - MVVM、WPF、C# 中的拇指拖动

windows - 如何通过 cmd 或批处理脚本查找哪些网络配置文件处于事件状态

networking - 四层防火墙功能

c++ - 构建 Boost_1_55_0 的示例异步 TCP 日间服务器

python - 使用 POX 创建 TCP 数据包

WCF 负载测试

c# - AuthorizationFilterAttribute 的正确用法

c# - 在 WebAPI 中绑定(bind)抽象操作参数

c# - 如何为新的 C# 类/接口(interface)编辑 Visual Studio 模板?

windows - 如何检测 Windows Server 2003 上的数据包丢失?