我想多次使用BufferedReader SOCKET

时间:2016-06-22 22:30:38

标签: java sockets

我的项目是客户端/服务器程序。客户端打开连接并发出控制台请求,直到用户输入"退出"。我第一次得到正确的答案。例如:

command: get oscar
response server: value: moncayo

如果我想要多个请求,BufferedReader始终坚持第一个命令请求。我不知道出了什么问题。

客户:

clientSocket = createSocket("127.0.0.1", 9990);
//clientSocket = createSocket(args[0], Integer.parseInt(args[1]));
System.out.println("Connect with the server.");
inputClient = new BufferedReader(new InputStreamReader(System.in));

//Now we need to read the input of the user
do{
    try {
        dataServer = new DataOutputStream(clientSocket.getOutputStream());
        //Read input of the user
        System.out.print("command: ");
        command = inputClient.readLine() +"\n";
        manipulateCommand(command, dataServer);
        System.out.println("Message Delivered.");
    } catch (IOException ex) {
        System.out.println(ex);
    }
}while(!command.equals("exit"));

服务器:

public void run() {
    System.out.println("Accepted Client : ID - " + clientID + " : Address - "
            + clientSocket.getInetAddress().getHostName());
    try {
        char [] x = {};
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
        out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
        while (isRunning) {
            if((inputclient  = in.readLine())!= null){
                System.out.println("Client Says :" + inputclient+"\n");
            }

manipulateCommand:

public static void manipulateCommand(String command, DataOutputStream dataServer){
    try {

        String type = null, key = null,value = null, message = null, result =null;
        StringTokenizer subString = new StringTokenizer(command);
            switch(subString.nextToken()){
                case "get":
                    type = "get";
                    key = subString.nextToken();
                    value= "";
                    break;
                case "set":
                    type = "set";
                    key = subString.nextToken();
                    value= subString.nextToken();
                    break;
                case "del":
                    type = "del";
                    key = subString.nextToken();
                    value= "";
                    break;
                case "list":
                    type = "list";
                    key="";
                    value="";
                    break;
                case "exit":
                    break;
                default:
                    break;
            }
        result = KVUtil.getXMLString(type, key, value,true);
        dataServer.writeBytes(result +"\n");
        dataServer.flush();
        //dataServer.close();
    } catch (IOException ex) {
        System.out.println("Error handling the input command");
    }
}  

0 个答案:

没有答案