Gua*_*apo 5 java authentication client communication
我目前正在玩java为桌面应用程序创建一个身份验证服务器,到目前为止,我已经能够让客户端和服务器像聊天服务器/客户端一样进行通信.
我确实知道我只有一小部分工作,有许多事情需要学习,但现在在这个阶段,我想知道如何进行身份验证.
例如,这是服务器代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class LoginServer
{
public static void main(String[] args) throws Exception {
int port = 7000;
int id = 1;
ServerSocket loginserver = null;
try
{
loginserver = new ServerSocket(port);
System.out.println("LoginServer started...");
}
catch (IOException e) {
System.out.println("Could not listen on port: " + port);
System.exit(-1);
}
while (true)
{
Socket clientSocket = loginserver.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
}
}
}
class ClientServiceThread extends Thread
{
Socket clientSocket;
int clientID = -1;
boolean running = true;
ClientServiceThread(Socket s, int i)
{
clientSocket = s;
clientID = i;
}
public void run()
{
System.out.println("Accepted Client : ID - " + clientID + " : Address - " + clientSocket.getInetAddress().getHostName());
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
while (running)
{
String clientCommand = in.readLine();
System.out.println("Client Says :" + clientCommand);
if (clientCommand.equalsIgnoreCase("quit"))
{
running = false;
System.out.print("Stopping client thread for client : " + clientID);
}
else
{
out.println(clientCommand);
out.flush();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我确实阅读了客户端发送的内容并将其输出到控制台,以及检查客户端是否已发送退出命令.
我想知道的是,如果用户和密码被发送,客户端只能连接到它?
或者我应该总是收到初始连接,并从那里收到验证信息,如果客户端没有发送它,让我们说3秒断开它们?
接收新连接并使用它验证用户的正确方法是什么?
Jon*_*han 10
你有正确的想法,但你需要把它想象成一个状态机.
客户端连接,然后它将需要进入登录状态,您希望它在那里发送身份验证信息.如果不正确或超时,请断开连接
如果正确,请转到命令处理状态.如果收到退出命令,请转到清除状态,或者只是断开连接.
这是一个大致的概述:
String line;
while ((line = in.readLine()) != null) {
switch (state) {
case login:
processLogin(line);
break;
case command:
processCommand(line);
break;
}
}
Run Code Online (Sandbox Code Playgroud)
你的processLogin功能可能如下所示:
void processLogin(String line) {
if (user == null) {
user = line;
}
else if (password == null) {
password = line;
}
else {
if (validUser(user, password)) {
state = command;
}
else {
socket.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
而你的processCommand功能:
void processCommand(String line) {
if (line.equals(...)) {
// Process each command like this
}
else if (line.equals("quit")) {
socket.close();
}
else {
System.err.println("Unrecognized command: " + line);
}
}
Run Code Online (Sandbox Code Playgroud)
该state实例变量很可能是一个枚举.您可以看到使用此模型将为您提供一些非常简单的可扩展性.例如,命令可能会将您置于不同的状态以处理特定的子命令.
| 归档时间: |
|
| 查看次数: |
17306 次 |
| 最近记录: |