Java 服务器无法正常关闭?

标签 java sockets

我已经尝试了一切,但我已无计可施。我正在编写一个简单的文件服务器,它将让用户远程登录,提供用户名并搜索为该用户提供的访问级别,然后显示文件列表,并且仅允许他们查看文件的内容具有足够的访问级别。此代码适用于服务器端,我仅使用 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();
    }

}
}

最佳答案

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

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

我认为这会让你朝着正确的方向发展。

关于Java 服务器无法正常关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120663/

相关文章:

c - SO_NOSIGPIPE 未声明

android - 如何在 Android 中创建原始套接字?

Python : 2 sockets, 从 A 发送到 B,从 B 发送到 A

java - 如何在 Java 中同时调用方法?

java - 在 hibernate 中使用 Criteria api 如何使用投影实现延迟加载列表?

java - 如何设置字段的值以便我可以从另一个类调用它?

c++ - 在 winsock2 中使用 C++ 创建套接字时出现问题

java - 迭代 Map 时出现 ConcurrentModificationException

java - OpenCV for android 与 openCV for windows 的不同结果

java - 将图像和视频文件从 android 发送到服务器并接收处理