通过套接字发送多个变量从客户端到服务器

问题描述:

我最近了解了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()); 

      } 

亲切的问候

阿里安

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

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

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

序列化对象,然后发送它。

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

现在使用的ObjectInput/OutputStream的读/写对象

请参阅本作的详细信息 - http://www.coderanch.com/t/205325/sockets/java/send-any-java-Object-through

如果你使用一个ObjectOutputStream你可以写整个对象。

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