簡體   English   中英

Java服務器無法正常關閉?

[英]Java server not closing properly?

我已經嘗試了一切,機智的結束了。 我正在編寫一個簡單的文件服務器,該服務器將允許用戶遠程登錄,提供用戶名並搜索賦予該用戶的訪問級別,然后顯示文件列表,並且僅允許他們查看文件內容(如果他們具有足夠的訪問級別。 這段代碼是針對服務器端的,我只是為客戶端使用PuTTY。

第一次運行可以按預期進行,

What is your username? paul

Filename:Access Level
chemistryhomework.txt:5
messageforbob.txt:0
nuclearlaunchcodes.txt:10
Which file would you like to read?
nuclearlaunchcodes.txt
The launch password is "UnlimitedBreadsticks"

然后我關閉PuTTY並嘗試第二次,並獲得此

Filename:Access Level
chemistryhomework.txt:5
messageforbob.txt:0
nuclearlaunchcodes.txt:10
Which file would you like to read?

什么時候應該從頭開始,並問我我的用戶名。 第三次嘗試顯示空白行,並在幾秒鍾后斷開連接。

包含所有文件名及其訪問級別的文件如下所示:

chemistryhomework.txt:5
nuclearlaunchcodes.txt:10
messageforbob.txt:0

我想可能在這里

//show list of files
int fileaccess;
outToClient.writeBytes("\n\rFilename:Access Level \n \r");
for (Entry<String, Integer> entry : files.entrySet()) //show all files and access levels
{
      String key = entry.getKey();
      Integer value = entry.getValue();
      outToClient.writeBytes(key + ":" + value + "\n \r");
}
while(!check)
{   
//ask user for file to read
outToClient.writeBytes("Which file would you like to read? \n \r");
String filetoread = inFromClient.readLine();
try
{
fileaccess = files.get(filetoread); //get access level requirement of file
    if (fileaccess > accesslevel) //if user is lacking the access level
    {
        outToClient.writeBytes("Error: You do not have sufficient privileges to access this file! \n \r");
        welcomeSocket.close();
        connectionSocket.close();
    }
    else
    {
        try //try to read the file, if it exists. Just a backup verification
        {
            file = new File(filetoread);
            Scanner scannerfile = new Scanner(file);
            while (scannerfile.hasNextLine()) 
                    {
                        String line = scannerfile.nextLine();
                        line=line.trim();
                        outToClient.writeBytes(line + "\n\r");
                    }
            outToClient.writeBytes("\n\r");
                    scannerfile.close();
        } 
    catch (FileNotFoundException e) 
    {
           outToClient.writeBytes("File not found! \n \r");
    }
    check = true;
    }
    }
    catch (NullPointerException e) //first line of defense for checking made-up files
{
    outToClient.writeBytes("Error: File does not exist! \n \r");
}
}
check = true;
//outToClient.writeBytes("Press enter to terminate session"); //user can see contents of file just in case disconnecting
//inFromClient.readLine();                                    //closes the window (like PuTTY)
inFromClient.close();
outToClient.close();
welcomeSocket.close();
connectionSocket.close();

但是,這是我的全部代碼。 我通過關閉所有內容來嘗試修復它,但徒勞無功。

package server;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.io.*;
import java.net.*;

import static java.lang.System.out;

public class Server 
{
static Map<String, Integer> files = new HashMap<String, Integer>(); //contains file names and the access level required to open them
static Map<String, Integer> users = new HashMap<String, Integer>(); //contains user names and the access level assigned to them

public static void main(String[] args) throws IOException
{
    out.println("Starting server...");

    //read datafile.txt into files hashmap
    File file = new File("datafile.txt");
    try
    {
        out.println("Reading datafile.txt");
        Scanner scannerdata = new Scanner(file);

        while (scannerdata.hasNextLine()) 
        {
            String line = scannerdata.nextLine();
            line.trim();
            String field[] = line.split(":");

            files.put(field[0], Integer.parseInt(field[1]));
        }
        scannerdata.close();
    } 
    catch (FileNotFoundException e) 
    {
        out.println("datafile.txt not found!");
    }
    ////////debug////////////
    //for (Entry<String, Integer> entry : files.entrySet()) 
    //{
    //  String key = entry.getKey();
    //  Integer value = entry.getValue();

    //  out.println(key);
    //  out.println(value);
    //}
    //int debugclearance = files.get("nuclearlaunchcodes.txt");
    //out.println(debugclearance);
    ////////debug////////////

    //read userfile.txt into users hashmap
    file = new File("userfile.txt");
    try
    {
        out.println("Reading userfile.txt");
        Scanner scannerusers = new Scanner(file);

        while (scannerusers.hasNextLine()) 
        {
            String line = scannerusers.nextLine();
            line.trim();
            String field[] = line.split(":");

            users.put(field[0], Integer.parseInt(field[1]));
        }
        scannerusers.close();
    } 
    catch (FileNotFoundException e) 
    {
        out.println("userfile.txt not found!");
    }
    ////////debug////////////
    //for (Entry<String, Integer> entry : users.entrySet()) 
    //{
    //  String key = entry.getKey();
    //  Integer value = entry.getValue();

    //  out.println(key);
    //  out.println(value);
    //}
    //int debugclearance = users.get("paul");
    //out.println(debugclearance);
    ////////debug////////////

    String clientinput;
    boolean check = false;
    int accesslevel = 0;        

    while(true)
    {
        ServerSocket welcomeSocket = null;
        Socket connectionSocket = null;
        BufferedReader inFromClient = null;
        DataOutputStream outToClient = null;

        try
        {
            //start connection
            //ServerSocket welcomeSocket = new ServerSocket(19000);
            //Socket connectionSocket = welcomeSocket.accept();

            welcomeSocket = new ServerSocket(19000);
            connectionSocket = welcomeSocket.accept();

            //BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            //DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

            inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            outToClient = new DataOutputStream(connectionSocket.getOutputStream());


            while(!check) //authenticate user
            {
                outToClient.writeBytes("What is your username?");
                outToClient.writeBytes(" ");
                String username = inFromClient.readLine();

                //alternate method I tried
                //if(users.get(username) == null)
                //{
                //  outToClient.writeBytes("Invalid username");
                //}
                //else
                //{
                //  check = true;
                //}

                try
                {
                    accesslevel = users.get(username);
                    check = true;
                }
                catch(NullPointerException e)
                {
                    outToClient.writeBytes("Incorrect username \n \r");
                    welcomeSocket.close();
                    connectionSocket.close();
                }
            }

            check = false;

            //debug
            //outToClient.writeBytes("It worked!");
            //outToClient.writeBytes(clientinput);

            //show list of files
            int fileaccess;
            outToClient.writeBytes("\n\rFilename:Access Level \n \r");
            for (Entry<String, Integer> entry : files.entrySet()) //show all files and access levels
            {
              String key = entry.getKey();
              Integer value = entry.getValue();
              outToClient.writeBytes(key + ":" + value + "\n \r");
            }
            while(!check)
            {   
                //ask user for file to read
                outToClient.writeBytes("Which file would you like to read? \n \r");
                String filetoread = inFromClient.readLine();
                try
                {
                    fileaccess = files.get(filetoread); //get access level requirement of file
                    if (fileaccess > accesslevel) //if user is lacking the access level
                    {
                        outToClient.writeBytes("Error: You do not have sufficient privileges to access this file! \n \r");
                        welcomeSocket.close();
                        connectionSocket.close();
                    }
                    else
                    {
                        try //try to read the file, if it exists. Just a backup verification
                        {
                            file = new File(filetoread);
                            Scanner scannerfile = new Scanner(file);
                            while (scannerfile.hasNextLine()) 
                            {
                                String line = scannerfile.nextLine();
                                line=line.trim();
                                outToClient.writeBytes(line + "\n\r");
                            }
                            outToClient.writeBytes("\n\r");
                            scannerfile.close();
                        } 
                        catch (FileNotFoundException e) 
                        {
                            outToClient.writeBytes("File not found! \n \r");
                        }
                        check = true;
                    }
                }
                catch (NullPointerException e) //first line of defense for checking made-up files
                {
                    outToClient.writeBytes("Error: File does not exist! \n \r");
                }
            }
            check = true;
            //outToClient.writeBytes("Press enter to terminate session"); //user can see contents of file just in case disconnecting
            //inFromClient.readLine();                                    //closes the window (like PuTTY)
            inFromClient.close();
            outToClient.close();
            welcomeSocket.close();
            connectionSocket.close();
        }
        catch(IOException e)
        {
            //out.println("Connection to client lost");
            inFromClient.close();
            outToClient.close();
            welcomeSocket.close();
            connectionSocket.close();
        }
        inFromClient.close();
        outToClient.close();
        welcomeSocket.close();
        connectionSocket.close();
    }

}
}

這是因為您一直使用相同的套接字。 另外,我認為您想通過多線程支持多個連接。 也許你可以看看這個答案?

創建一個套接字服務器,它允許通過線程和Java進行多個連接

我認為這將使您朝正確的方向發展。

您對變量“ check”的管理不當。 您將其設置為true以退出循環,並跳過身份驗證過程。 嘗試為這些部分使用兩個不同的變量,以避免這種類型的混淆。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM