简体   繁体   English

使用相同的网络流和套接字连接从C#客户端向Java服务器发送多个byte []时挂起

[英]Hanging when sending multiple byte[] from a C# client to a Java server using the same Network Stream and Socket connection

I've written a file uploader designed to send a file of program code from a C# client to a Java server. 我编写了一个文件上传器,旨在将程序代码文件从C#客户端发送到Java服务器。 The server requires a valid username and password to be submitted prior to accepting the file upload. 在接受文件上传之前,服务器需要提交有效的用户名和密码。

Independently both the security (username and password) and the file uploader work correctly. 安全性(用户名和密码)和文件上传器都可以独立正常工作。 However when I attempt to combine the two the code freezes on the C# client after receiving a 'true' boolean response back from the server (indicating a correct username and password). 但是,当我尝试将两者结合时,在收到服务器返回的“ true”布尔响应(指示正确的用户名和密码)后,代码在C#客户端上冻结。 The relevant code from the client and server is attached. 附加了来自客户端和服务器的相关代码。

C# Client C#客户端

public static string sendValidatedFile(string username, string password, string path) {

        string inputString = "NotSent";

        try {

            TcpClient client = new TcpClient("127.0.0.1", 42000);

            StreamReader input = new StreamReader(stream);

            Stream securityStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(username + "_" + password + "_\n"));

            byte[] bufferA = new byte[securityStream.Length];
            securityStream.Read(bufferA, 0, bufferA.Length);

            stream.Write(bufferA, 0, bufferA.Length);
            stream.Flush();

            inputString = input.ReadToEnd();
            bool result = bool.Parse(inputString);

            if (result) {

                print("Login Accepted");

                Stream fileStream = File.OpenRead(path);

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

                // This is where the code seems to lock up
                stream.Write(buffer, 0, buffer.Length);
                stream.Flush();

                inputString = input.ReadToEnd();

            }

            else {

                inputString = "Invalid Username or Password";

            }

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

        }

        catch (SocketException e) {

            print("Error" + e);

        }

        catch (IOException e) {

            print("Error" + e);

        }

        return inputString;

    }

Java Server Java服务器

public void run() {

try {

  // Get username and password
    byte[] byteArrayJAR = new byte[filesize];
    byte[] byteArraySecurity = new byte[filesize];
    InputStream input = socket.getInputStream();
    PrintWriter output = new PrintWriter(socket.getOutputStream());

    int bytesSecurity = input.read(byteArraySecurity, 0, byteArraySecurity.length);
    int currentByte1 = bytesSecurity;

    if (input.available() > 0) {

        do {

            bytesSecurity = input.read(
                    byteArraySecurity,
                    currentByte1,
                    (byteArraySecurity.length - currentByte1));

            if (bytesSecurity >= 0) {

                currentByte1 += bytesSecurity;

            }
        }

        while (bytesSecurity > -1);
    }

    String securityString = new String(byteArraySecurity).trim();
    String[] authenticationString = securityString.split("_");
    String username = authenticationString[0];
    String password = authenticationString[1];

  // Validate the username and password with a stored database
    if (security.validateUser(username, password)) {

       // Inforn the client their username and password were accepted
        output.println(true);
        output.flush();

      // Get the program code file
        int bytesRead = input.read(byteArrayJAR, 0, byteArrayJAR.length);
        int currentByte = bytesRead;

       if (input.available() > 0) {

                do {

                   bytesRead = input.read(
                     byteArrayJAR,
                            currentByte,
                            (byteArrayJAR.length - currentByte));

                if (bytesRead >= 0) {

                        currentByte += bytesRead;

                    }
             }

                 while (bytesRead > -1);

     }

      // Inform the client that the code was received
        output.println("Success");
        output.flush();

    }

    else {

      // Inform the client their username or password was incorrect
        output.println(false);
        output.flush();

    }

  // Disconnect from client
    output.flush();
    output.close();
    input.close();
    socket.close();

}

catch (IOException e) {

    e.printStackTrace();

}

} }

Can anybody see anything wrong with the above that could be causing my code to hang? 有人可以看到上述任何错误导致我的代码挂起吗? There is definately be data for the C# client to transmit on both instances. 肯定有数据可供C#客户端在两个实例上传输。 Is there a reason why two byte arrays can't be sent from the same Network Stream in C#? 为什么不能从C#的同一网络流中发送两个字节数组?

I'd appreciate any help anybody can offer in getting the above code to work without hanging. 任何人在使以上代码正常工作时都可以提供的任何帮助,我将不胜感激。

Regards, 问候,

Midavi. Midavi。

You are using input.ReadToEnd() twice. 您正在使用input.ReadToEnd()两次。 A stream only has one end; 流只有一端。 I suspect the first of these is out of place, and should be replaced with more direct reading - or at best, a ReadLine(). 我怀疑其中第一个不适当,应该替换为更直接的阅读-最好是ReadLine()。

If the conversation here depends on multiple messages between client and server, you might also want to check if nagle is enabled, as it could be that one of the messages is still buffered and has not actually been sent yet (Flush() does nothing on a network stream) - you may have to set NoDelay (or the equivalent) for the socket. 如果此处的对话依赖于客户端和服务器之间的多条消息,则您可能还需要检查是否启用了nagle,因为可能其中一条消息仍在缓冲中并且尚未实际发送(Flush()不会执行任何操作网络流)-您可能必须为套接字设置NoDelay(或等效设置)。 The default behaviour is to buffer small messages to prevent flooding the network with lots of tiny packets. 默认行为是缓冲小消息,以防止大量小数据包淹没网络。

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

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