【问题标题】:Sending more than one variables from client to server through socket通过套接字从客户端向服务器发送多个变量
【发布时间】:2012-02-26 22:00:28
【问题描述】:

我最近了解了 Java 中的套接字以及通过套接字从客户端到服务器来回发送信息。 我想要实现的是从客户端向服务器发送“用户名”和“密码”,然后根据数据库中的数据检查这些变量。

将这两个单独值的值发送到服务器以便在服务器端进行验证的最佳方法是什么?

客户端

clientSocket = new Socket("192.168.56.1", 7777);

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


    //starting the thread
    while(runner == null)
    {
        runner = new Thread(this);

        runner.start();
    }
}
public void run()
{
    String userNameAdminLogin;
    String passwordAdminLogin;
    while(runner == Thread.currentThread())
    {
        userNameAdminLogin = txtUserName.getText();
        passwordAdminLogin = txtPassword.getText();

        out.println(userNameAdminLogin);
        out.println(passwordAdminLogin);
    }

服务器端

while(listening)
            {
                clientSocket = ServerSoc.accept();


                in = new DataInputStream(clientSocket.getInputStream());

                BufferedReader is = new BufferedReader(new InputStreamReader(in));

                os = new PrintStream(clientSocket.getOutputStream());

                //How can I save the two seperate cases of data in variables on server side?
                System.out.println(is.readLine());

            }

亲切的问候

阿里安

【问题讨论】:

    标签: java sockets


    【解决方案1】:

    如果你在一侧写两行,你显然应该在另一侧读两行:

    String name = is.readLine();
    String password = is.readLine();
    

    【讨论】:

      【解决方案2】:

      你可以拥有一个拥有用户名和密码作为属性的对象。

      序列化对象然后发送。

      class User implements Serializable {  
      String userName ;
      String Password ;
      ... 
      }  
      

      现在使用 ObjectInput/OutputStream 来读取/写入对象

      请参阅此以获取更多信息 - http://www.coderanch.com/t/205325/sockets/java/send-any-java-Object-through

      【讨论】:

        【解决方案3】:

        如果您使用 ObjectOutputStream,您可以编写整个对象。

        这些对象必须是可序列化的

        【讨论】:

          猜你喜欢
          • 2013-12-26
          • 2016-08-31
          • 1970-01-01
          • 1970-01-01
          • 2019-08-08
          • 1970-01-01
          • 1970-01-01
          • 2013-04-01
          • 1970-01-01
          相关资源
          最近更新 更多