Java 简单服务器未正确关闭?

Java 简单服务器未正确关闭?,java,sockets,Java,Sockets,我什么都试过了,但我已经束手无策了。我正在编写一个简单的文件服务器,它将允许用户telnet进入,提供一个用户名并搜索给定给该用户的访问级别,然后显示一个文件列表,并且仅允许他们在具有足够访问级别的情况下查看文件的内容。这段代码是针对服务器端的,我只是针对客户端使用PuTTY 第一次运行按预期运行 What is your username? paul Filename:Access Level chemistryhomework.txt:5 messageforbob.txt:0 nucle

我什么都试过了,但我已经束手无策了。我正在编写一个简单的文件服务器,它将允许用户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"
然后我关上油灰,再试一次,得到这个

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();
//显示文件列表
int文件访问;
outToClient.writeBytes(“\n\r文件名:访问级别\n\r”);
for(条目:files.entrySet())//显示所有文件和访问级别
{
String key=entry.getKey();
整数值=entry.getValue();
outToClient.writeBytes(键+“:“+值+”\n\r”);
}
同时(!检查)
{   
//要求用户读取文件
outToClient.writeBytes(“您要读取哪个文件?\n\r”);
字符串filetoread=informclient.readLine();
尝试
{
fileaccess=files.get(filetoread);//获取文件的访问级别要求
if(fileaccess>accesslevel)//如果用户缺少访问级别
{
outToClient.writeBytes(“错误:您没有足够的权限访问此文件!\n\r”);
welcomeSocket.close();
connectionSocket.close();
}
其他的
{
尝试//尝试读取文件(如果存在)。只是备份验证
{
文件=新文件(filetoread);
扫描仪scannerfile=新扫描仪(文件);
while(scannerfile.hasNextLine())
{
String line=scannerfile.nextLine();
line=line.trim();
outToClient.writeBytes(行+“\n\r”);
}
outToClient.writeBytes(“\n\r”);
scannerfile.close();
} 
catch(filenotfounde异常)
{
outToClient.writeBytes(“未找到文件!\n\r”);
}
检查=正确;
}
}
catch(NullPointerException e)//检查组合文件的第一道防线
{
outToClient.writeBytes(“错误:文件不存在!\n\r”);
}
}
检查=正确;
//outToClient.writeBytes(“按enter键终止会话”)//用户可以看到文件的内容,以防万一
//refromclient.readLine()//关闭窗口(如油灰)
informclient.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.io.BufferedReader;
导入java.io.DataOutputStream;
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.Map;
导入java.util.Map.Entry;
导入java.util.Scanner;
导入java.io.*;
导入java.net。*;
导入静态java.lang.System.out;
公共类服务器
{
静态映射文件=new HashMap();//包含文件名和打开它们所需的访问级别
static Map users=new HashMap();//包含用户名和分配给它们的访问级别
公共静态void main(字符串[]args)引发IOException
{
out.println(“启动服务器…”);
//将datafile.txt读入hashmap文件
File File=新文件(“datafile.txt”);
尝试
{
println(“读取datafile.txt”);
扫描仪scannerdata=新扫描仪(文件);
while(scannerdata.hasNextLine())
{
String line=scannerdata.nextLine();
line.trim();
字符串字段[]=行。拆分(“:”);
file.put(字段[0],Integer.parseInt(字段[1]);
}
scannerdata.close();
} 
catch(filenotfounde异常)
{
println(“未找到datafile.txt!”);
}
////////调试////////////
//for(条目:files.entrySet())
//{
//String key=entry.getKey();
//整数值=entry.getValue();
//out.println(键);
//out.println(值);
//}
//int debugclearance=files.get(“nuclearlaunchcodes.txt”);
//out.println(调试许可);
////////调试////////////
//将userfile.txt读入用户hashmap
file=新文件(“userfile.txt”);
尝试
{
println(“读取userfile.txt”);
扫描仪scannerusers=新扫描仪(文件);
while(scannerusers.hasNextLine())
{
String line=scannerusers.nextLine();
line.trim();
字符串字段[]=行。拆分(“:”);
user.put(字段[0],Integer.parseInt(字段[1]);
}
scannerusers.close();
} 
catch(filenotfounde异常)
{
println(“找不到userfile.txt!”);
}
////////调试////////////
//for(条目:users.entrySet())
//{
//String key=entry.getKey();
//整数值=entry.getValue();
//out.println(键);
//out.println(值);
//}
//int debugclearance=users.get(“paul”);
//out.println(调试许可);
////////调试////////////
字符串客户端输入;
布尔检查=假;
int accesslevel=0;
while(true)
{
ServerSocket welcomeSocket=null;
套接字连接Socket=null;
BufferedReader INFOROMCLIENT=null;
DataOutputStream outToClient=null;
尝试
{
//启动连接
//ServerSocket welcomeSocket=新的ServerSocket(19000);
//套接字连接Socket=welcomeSocket.accept();
welcomeSocket=新服务器插座(19000);
骗局