Java服务器没有正常关闭?

时间:2014-03-01 21:34:03

标签: java sockets

我已经尝试过所有事情,而且我已经结束了。我正在编写一个简单的文件服务器,让用户telnet,提供用户名并搜索给该用户的访问级别,然后显示文件列表,只允许他们查看文件的内容有足够的访问级别。这段代码用于服务器端,我只是为客户端使用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();
    }

}
}

2 个答案:

答案 0 :(得分:0)

这是因为你继续使用相同的套接字。另外我认为您希望支持多线程的多个连接。也许你可以看看这个答案?

Creating a socket server which allows multiple connections via threads and Java

我认为这会让你朝着正确的方向前进。

答案 1 :(得分:0)

您对变量'check'管理不善。您将其设置为true以退出循环,并跳过身份验证过程。尝试对这些部分使用两个不同的变量来避免这种混淆。

相关问题