不错,还有我有一个方法,你可以试试,也许,如果它是有用的,你可以考虑为您实现。
首先,我将创建一个实体来处理这些值并将其填入传入数据。
class UserAuth {
private String username;
private String password;
//Consider here your getters and setters, I am not including them
}
我将使用实体作为在发送方法的参数,也许你可以填充它,就像这样:
UserAuth attemptingUser = new UserAuth(...)
ObjectInputStream的正常工作对这些类型的场景。如果你仍然想使用字符串,你可以使用BufferedReader并尝试将你的用户名和密码合并为一个字符串,并使用.readLine()方法获得(用逗号分隔),然后使用String方法,例如Split,但我发现这可能需要更多的时间,如果你用一个对象处理它应该会更好。但这取决于你想添加到你的应用程序的复杂性:)。
class AuthClient {
public void sendMsg(UserAuth attemptingUser) {
String host = "localhost";
int port = 2055;
//1. Create the socket
Socket sender = new Socket(host, port);
//2. Create an object output stream to write the object into the stream
ObjectOutputStream outputWriter = new ObjectOutputStream(sender.getOutputStream());
//3. Write (send the object)
outputWriter.writeObject(attemptingUser);
//4. Close
outputWriter.close();
sender.close();
}
}
class AuthServer {
ServerSocket ss = new ServerSocket(2055);
public void receiveMsg() {
//1. Accept the connection
Socket conn = ss.accept();
//2. Receive the flow
ObjectInputStream readStream = new ObjectInputStream(conn.getInputStream());
//3. Read the object
UserAuth userReceived = readStream.readObject();
//4. Verify against file, db or whatever
if (userReceived.getUsername().equals("admin") && userReceived.getPassword().equals("admin")) {
//Authentication
}
}
}
(这被添加为我编辑你问我的意见的部分)
public void sendMsg(String username, String password) {
String host = "localhost";
int port = 2055;
//1. Create the socket
Socket sender = new Socket(host, port);
//2. Create the UserAuth object based on the parameters you received
UserAuth myuser = new UserAuth();
myuser.setUsername(username);
myuser.setPassword(password);
//3. Follow same instructions for the creation of ObjectOutputStream...
ObjectOutputStream objectWriter = new ObjectOutputStream(sender.getOutputStream());
objectWriter.writeObject(myuser);
//That is what I would use if I keep your structure
}
如果你想使用字符串,让您的结构,我将简化和降低我的影响/ O通过使用String方法。既然你知道你总是期待用户/密码,我会合并你的两个参数在一个单一的字符串或使用特殊的字符和在服务器端处理StringTokenizer类。或者,也许可以用“分割”方法来处理。你在这里有很多选择。
到目前为止,这将是我面对您遇到的问题的方法。希望它以某种方式帮助。最好的问候和快乐的编码:)。