Java网络服务器无法响应客户端

时间:2014-05-30 13:20:53

标签: java networking

我正在尝试构建一个网络版的Battleship,并且遇到了一个问题,我的服务器似乎没有接收到客户端的请求,或者服务器在发送响应时遇到问题给客户。我所知道的是我的服务器在accept()上执行一个新线程,但不幸的是我不知道在那之后出了什么问题。我无法找到使用eclipse调试新线程的方法。下面是我目前为我的三个班级编写的代码。假设客户输入1以请求查看可用游戏列表。客户端在等待响应时挂起。服务器应该打开case" list"。对我出错的地方有任何帮助都很棒。

public class Server {
    //global variables for clients to call whenever
    public static ArrayList<Socket> ClientArray = new ArrayList<Socket>();
    public static ArrayList<String> ClientNameArray = new ArrayList<String>();
    public static ArrayList<Socket> WaitingClients = new ArrayList<Socket>();
    public static ArrayList<String> WaitingPlaterNames = new ArrayList<String>();

    public static void main(String[] args){
        try {

            final int PORT = 7334;
            ServerSocket SERVER = new ServerSocket(PORT);
            System.out.println("waiting on client connections");

            //infinite accept
            while(true){
                Socket sock = SERVER.accept();
                ClientArray.add(sock);
                System.out.println("Client added");
                addName(sock);

                ServerGame serverSide = new ServerGame(sock);
                serverSide.start();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addName(Socket sock){
        try {
            BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String user = input.readLine();
            ClientNameArray.add(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

然后ServerGame:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerGame extends Thread {
    private Socket sock;
    private BufferedReader input = null;
    private PrintWriter out = null;
    String commandMessage = "";

    public ServerGame(Socket sock) {
        this.sock = sock;
    }

    private void checkConnection() {
        if (!sock.isConnected()) {
            //if not connected anymore remove from client list
            for (int i = 0; i < Server.ClientArray.size(); i++) {
                if (Server.ClientArray.get(i) == sock) {
                    Server.ClientArray.remove(i);
                    Server.ClientNameArray.remove(i);
                }
            }
            //check if client started new game and is waiting. If so
            //remove them from that list too
            for(int j = 0; j < Server.WaitingClients.size(); j++){
                if(Server.WaitingClients.get(j) == sock){
                    Server.WaitingClients.remove(j);
                    Server.WaitingPlaterNames.remove(j);
                }
            }
        }
    }

    private void parseAndSend(String commandMessage) {
        boolean found = false;
        String[] message = commandMessage.split("\\s+");
        // 3rd argument in message is always the command
        switch (message[2]) {

        // initial inquiry cases
        case "list":
            String inquiry;
            if(Server.WaitingPlaterNames.size() != 0){
                inquiry = "Available Games: " + Server.WaitingPlaterNames;
            }
            else{
                inquiry = "No Available Games";
            }
            try {
                out = new PrintWriter(sock.getOutputStream());
                out.println(inquiry);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            break;
        case "newgame":
            break;
        case "join":
            break;

        // game commands
        case "connection":
            // make output to other player's socket
            for (int i = 0; i < Server.ClientArray.size(); i++) {
                if (Server.ClientNameArray.get(i).equals(message[1])) {
                    try {
                        // set outputstream to other player's socket
                        out = new PrintWriter(Server.ClientArray.get(i)
                                .getOutputStream());
                        found = true;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            // if you didn't find the player send back to sender fail
            if (!found) {
                try {
                    out = new PrintWriter(sock.getOutputStream());
                    String failMessage = "attempt connection failure";
                    out.println(failMessage);
                    return;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // is this a request or confirmation?
            if (message[3].equals("request")) {
                String sendMessage = message[0] + " " + message[1]
                        + " connection request";
                // send it to opponent's socket
                out.println(sendMessage);
                return;
            } else { // finalization from other side to server
                String sendMessage = message[0] + " " + message[1]
                        + " connection finalized";
                out.println(sendMessage);
                return;
            }
        case "move":
            break;
        case "chat":
            break;
        case "failure":
            break;
        default:
            return;

        }
        out.flush();
    }

    @Override
    public void run() {
        try {
            input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            commandMessage = input.readLine();
            System.out.println("Command Message Received : " + commandMessage);
            while (!commandMessage.equals("DISCONNECT")) {
                checkConnection();

                parseAndSend(commandMessage);
                commandMessage = input.readLine();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        finally {
            try {
                System.out.println("Closing Connection...");
                if (null != input) {
                    input.close();
                }
                if (null != out) {
                    out.close();
                }
                if (null != sock) {
                    sock.close();
                    System.out.println("Socket Closed.");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

最后我的客户:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;


public class Client {
    public static void main(String[] args){
        InetAddress address = null;
        Socket socket = null;
        String commandMessage = "";
        String myUsrname = "";
        String opponentName = "";
        BufferedReader input = null;
        PrintWriter out = null;
        BufferedReader myInput = null;
        final int PORT = 7334;
        try {
            //get my address for socket
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        System.out.println("Welcome to BattleCarrier! (BattleShip was taken)");
        System.out.println("************************************************");
        System.out.println("************************************************");
        System.out.println();
        System.out.println("To Register, please type in a Username.");

        myInput = new BufferedReader(new InputStreamReader(System.in));

        String consoleCommand = "";
        while(consoleCommand.equals("")){
            try {
                consoleCommand = myInput.readLine();

                if(consoleCommand.equals("")){
                    System.out.println("How about a real username???");
                    continue;
                }

                myUsrname = consoleCommand;
                System.out.println("Your Username has been set to " + myUsrname + ".");
                System.out.println("Setting up a connection with the server...");

                //set up the socket
                if(null != address){
                    socket = new Socket(address, PORT);
                    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    out = new PrintWriter(socket.getOutputStream());

                    System.out.println("Client Address: " + address);
                    System.out.println("Connection Established with Server");
                }
            } catch (IOException e) {
                System.out.println("Server may not be reachable. Please Try again later.");
                System.out.println("Goodbye.");
                System.exit(0);
            }
        }

        System.out.println();
        System.out.println("Please choose from the following commands:");
        System.out.println("*********************************************************");
        System.out.println("Type: 1 for available games.");
        System.out.println("Type: 2 to start a new game.");
        System.out.println("Type: 3 to join someone else.");
        System.out.println("*********************************************************");
        System.out.println("Type: \"DISCONNECT\" at any time to unregister and quit.");
        System.out.println("*********************************************************");

        try {
            consoleCommand = myInput.readLine();
            while(!consoleCommand.equals("DISCONNECT")){
                switch(consoleCommand){
                case("1"):
                    System.out.println("1 was selected");
                    String inquiry = ". . list";
                    out.println(inquiry);
                    break;
                case("2"):
                    break;
                case("3"):
                    break;
                default:
                    System.out.println("Not a valid command. Please try again.");
                    break;
                }
                if(null != out){
                    out.flush();
                }
                String response = input.readLine();
                System.out.println("Server Response: " + response);
                consoleCommand = myInput.readLine();
            }
            //write the code for disconnect here
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

1 个答案:

答案 0 :(得分:-1)

addName(袜子); Server.java中的函数有一个input.readline()在客户端上等待导致挂起...