从服务器/客户端应用程序(Java)获取数组

时间:2013-09-15 22:35:23

标签: java arrays database

所以我在我的应用程序和数据库之间运行了一个服务器/客户端层应用程序。我想从服务器获取一个数组。我将粘贴一些代码,我认为这些代码足以让您了解正在发生的事情:

我向服务器发送了在数据库中搜索的关键字(用户及其密码)

    fromUser = Musername + "," + Password;
    out.println(fromUser);

以下是服务器的代码:

  public class Server {

    public static String[] theOutput;
    public static String inputLine;
    public static String[] string_array;
    public static String output = "";

    public static String[] process(String Input) throws Exception {

        String[] data = Input.split(",");

        // Call database class to get the results and store them into the array
        load_login pridobi = new load_login();
        theOutput = pridobi.nalozi(data[0], data[1]);

        return theOutput;

    }

    public static void main(String[] args) throws Exception {

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.exit(1);
        }

        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.exit(1);
        }

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(
                clientSocket.getInputStream()));

// get the username and password
        inputLine = in.readLine();

        if (inputLine.length() != 0) {

            string_array = process(inputLine);
        }

// And here I would like to do something like that :/
        out.println(string_array);

    }
}

PS:注意一些数组元素实际上是长文本。

1 个答案:

答案 0 :(得分:0)

我建议你在技术上使用其他。 如果您发送到服务器的用户名和密码包含“,”,那么会发生什么。 拆分时,您获得了错误的数据。

  

发送前:示例:

String username = URLEncoder.encoder("myusername", "utf-8");
String password = URLEncoder.encoder("mypassword", "utf-8");
String dataToSend = username + "," + password;
  

在您的服务器中:

String[] data = Input.split(",");
data[0] = URLDecoder.decoder(data[0],"utf-8");
data[1] = URLDecoder.decoder(data[1],"utf-8");
  

服务器应该响应这样的字符串:

String responseData =  URLEncoder.encoder(theOutput[0], "utf-8") + "," + URLEncoder.encoder(theOutput[1], "utf-8");
out.println(responseData);
  

客户端读取响应如下:

String dataReceived = inputLine = in.readLine();
String data[] = dataReceived.split(",");
data[0] = URLDecoder.decoder(data[0],"utf-8");
data[1] = URLDecoder.decoder(data[1],"utf-8");