使用hashmap java

时间:2015-11-21 22:28:32

标签: java hashmap server client

我试图向特定客户发送消息,例如客户端1想要向客户端2发送消息。客户端1向服务器发送消息,服务器计算答案并将其发送给显示它的客户端2。 我使用HashMap存储每个客户端。它编译,但是当我运行它时,它在发送消息时崩溃并显示

  

通信服务器问题

我认为错误发生在我发送邮件的循环中,但我看不出它有什么问题,我是否需要在客户端使用单独的代码?

服务器:

import java.net.*; 
import java.util.*;
import java.io.*; 

public class EchoServer2b extends Thread implements Runnable{   
    protected static Socket clientSocket;
    static String [] logs = new String[100];
    //protected static ArrayList<PrintWriter> writers = new ArrayList<PrintWriter>();
    static HashMap<String, Socket> clients = new HashMap<String, Socket>();
    static int arrayPos = 0;
    static int i, clientCount = 0;
    static String clientID;
    static String receiver="",actualMessage="";
    public static void main(String[] args) throws IOException{
        ServerSocket serverSocket = null; 
        try{ 
            serverSocket = new ServerSocket(10008); 
            System.out.println ("Connection Socket Created");
            try { 
                while (true)
                {
                    System.out.println ("Waiting for Connection");
                    new EchoServer2b (serverSocket.accept());
                    ++clientCount;
                    clientID = Integer.toString(clientCount);
                    clients.put(clientID, clientSocket);
                }
            } 
            catch (IOException e) 
            { 
                System.err.println("Accept failed."); 
                System.exit(1); 
            } 
        } 
        catch (IOException e) 
        { 
            System.err.println("Could not listen on port: 10008."); 
            System.exit(1); 
        } 
        finally{
            try{
                serverSocket.close(); 
            }
            catch (IOException e)
            { 
                System.err.println("Could not close port: 10008."); 
                System.exit(1); 
            } 
        }
    }

    private EchoServer2b (Socket clientSoc){
        clientSocket = clientSoc;
        start();
    }   

    public void run(){
        System.out.println ("New Communication Thread Started");
        try{
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); 
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            System.out.println("Client ID: " + clientID);
            String inputLine; 
            while ((inputLine = in.readLine()) != null) { //reading
                System.out.println(inputLine);
                String message[]=inputLine.split(", ");
                logs[arrayPos] = message[1]; //keep record of all commands sent to server
                arrayPos++; //update array position
                receiver=message[0];
                actualMessage=message[1];

                if (actualMessage.equals("Bye.")) //break if client enters 'Bye."
                    break;
                if(actualMessage.equals("Logs.")){ //print out contents of logs if any client enters 'Logs'
                    for(i=0; i<arrayPos; i++){
                        System.out.println("Log"+ i + ": " + logs[i]);
                    }         
                    break;
                } 
                for (Map.Entry<String, Socket> entry: clients.entrySet()) {
                    String clientName = entry.getKey();
                    if(clientName.equals(receiver))
                    {
                        Socket socket = entry.getValue();    
                        try {
                             PrintWriter receiverOut = new PrintWriter(socket.getOutputStream(), true); 
                             //DataOutputStream receiverDOS = new DataOutputStream(socket.getOutputStream());
                             int x, y, result;
                             String num1, num2, operator;
                             String [] splitStrings = actualMessage.split(" ");
                             num1 = splitStrings[0];
                             x = Integer.parseInt(num1);
                             operator = splitStrings[1];
                             num2 = splitStrings[2];
                             y = Integer.parseInt(num2);
                             switch(operator){
                             case "+":
                             result = x + y;
                             System.out.println ("Server: " + result); 
                                 receiverOut.println(result);
                                 break;
                             case "-":
                             result = x - y;
                             System.out.println ("Server: " + result); 
                                 receiverOut.println(result);
                                 break;
                             case "*":
                             result = x * y;
                             System.out.println ("Server: " + result); 
                                 receiverOut.println(result);
                                 break;
                             case "/":
                             result = x / y;
                             System.out.println ("Server: " + result); 
                                 receiverOut.println(result);
                                 break;
                             default:
                                 System.out.println("Please enter a more simple equation using one of the 4 main operators i.e. '+, -, *, /'");
                                     break;
                             }

                             receiverOut.flush();
                             receiverOut.close(); 
                             socket.close();
                        } catch (IOException e) {
                              e.printStackTrace();
                        }
                    } 
                } 
            }
            out.flush();
            out.close(); 
            in.close(); 
            clientSocket.close();
        }
        catch (IOException e){ 
            System.err.println("Problem with Communication Server");
            e.printStackTrace();
            System.exit(1); 
        }
    }

    public void sendMessage(String receiver, String actualMessage) {        

    }
} 

客户端:

import java.io.*;
import java.net.*;
public class EchoClientB {
    static boolean flag = true;
    public static void main(String[] args) throws IOException{
        String serverHostname = new String ("127.0.0.1");
        if (args.length > 0)
           serverHostname = args[0];
        System.out.println ("Attemping to connect to host " + serverHostname + " on port 10008.");
        Socket echoSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try{
            echoSocket = new Socket(serverHostname, 10008);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
        }catch (UnknownHostException e){
            System.err.println("Don't know about host: " + serverHostname);
            System.exit(1);
        } catch (IOException e){
            System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
            System.exit(1);
        }

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String userInput = "";
        System.out.println ("Type Message (\"Bye.\" to quit)");
        //System.out.println("Enter a simple math equation i.e. 2 + 2 separated by a space…");
        System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
        System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
        while(true){
            if(userInput.equals("Bye.")){
                break;
            }
            if((userInput = stdIn.readLine()) != null){
                out.println(userInput);
                userInput = in.readLine();
                System.out.println("echo: " + userInput);
                System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
                System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
                out.flush();
            }
            else if(in.ready()){
                userInput = in.readLine();
                System.out.println("echo: " + userInput);
                System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
                System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
                out.flush();
            }
        }

        out.close();
        in.close();
        stdIn.close();
        echoSocket.close();
    }
}

2 个答案:

答案 0 :(得分:0)

你得到一个IOException,因为你正在关闭你想要从第140行读取的流。我建议你在范围内移动所有蒸汽关闭(第142行)。

答案 1 :(得分:0)

在服务器运行方法中,在您向其中一个客户端发送消息的代码的末尾,您有

            out.flush();
            out.close(); 
            in.close(); 
            clientSocket.close(); 
        }
    }
    catch (IOException e){ 
        System.err.println("Problem with Communication Server");
        System.exit(1); 
    } 

这是关闭套接字,这就是你获得异常的原因。您可能希望将此块移动到您确实要关闭客户端连接的位置