【问题标题】:BufferedReader readLine() method not running multiple times, Java, Socket, Threads [duplicate]BufferedReader readLine()方法未多次运行,Java,Socket,线程[重复]
【发布时间】:2016-11-13 05:38:49
【问题描述】:

我正在做一个学校项目,我小组提出的主题是终端网络信使应用程序(类似于whatsapp,肯定不那么复杂)。我的问题是我的BufferedReader 对象在收到客户端后没有读取下一个输入。我第一次向服务器发送信息时,BufferedReader 可以工作,但在那之后的任何时候都没有任何反应。我能做些什么来解决这个问题?我是ThreadsSockets 的新手,所以假设我几乎一无所知,请回答。先感谢您。 (PS.如果我的详细信息中缺少任何代码,请务必告诉我,我会在收到消息后立即添加)

客户端主:

package COE528.MajorProject;

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

public class ClientUIManager {
private Client user = null;
private Socket userSocket = null;
private BufferedReader serverScannerInput, scanner = null;
private PrintWriter output = null;


public static ClientUIManager instance;

private ClientUIManager(){
    try{
        userSocket = new Socket("localhost", 4000);
        serverScannerInput = new BufferedReader(new InputStreamReader(userSocket.getInputStream()));
        output = new PrintWriter(userSocket.getOutputStream(), true);
        scanner = new BufferedReader(new InputStreamReader(System.in)); 
    }catch(IOException ex){
        ex.printStackTrace();
    }
}

public static ClientUIManager getInstance(){
    if(instance == null)
        instance = new ClientUIManager();
    return instance;
}

public static void main(String[] args) {
    instance = ClientUIManager.getInstance();
    try{
    String userInput;
    String[] breakUp;
    String serverInput;
    System.out.println("Type \"login\" to login or \"create\" to create a new account ");
    while(!((userInput = instance.scanner.readLine()).equals("/exit"))){
        System.out.println("userInput: " + userInput); //GET RID OF LATER
        breakUp = userInput.split(" ");
        //establish connection and respond acordingly
        if(userInput.equals("login")){
            System.out.println("Please enter login information: \"Username Password\" ");
            userInput = instance.scanner.readLine();
            instance.login(userInput);
        }
        if(userInput.equals("create")){
            System.out.println("Please create new account information: \"Login Password\" ");
            userInput = instance.scanner.readLine();
            instance.createClient(userInput);
        }
        if(instance.userLoggedIn()){
            //private messaging
            if(userInput.charAt(0)== '@'){
                if(breakUp.length > 1)
                    instance.privateMessage(userInput);
                else
                    System.out.println("Not enough agruments please enter @Username message");
            }
            if(breakUp[0].equals("/add")){
                if(breakUp.length ==2)
                    instance.addFriend(breakUp[1]);
                else
                    System.out.println("Not enough agruments please enter a new command");
            }
            if(breakUp[0].equals("/unfriend")){
                instance.removeFriend(breakUp[1]);
            }
        }
    }
    instance.output.println("/exit");
    System.out.println("Closing program");
}catch(IOException ex){
        ex.printStackTrace();
        System.exit(1);
    }
}

public boolean userLoggedIn(){
    //OVERVIEW: checks if user has logged in or not.
    if(user == null)
        return false;
    else
        return true;
}

public void privateMessage(String previousInput){
   //OVERVIEW: sends private message to another user (name inside string). Checks checkPersonOnline first: true sends message / false responds with message telling recipient is offline
   String checkUsername;
   String[] checkUsernameArray;
   checkUsernameArray = previousInput.split(" ");
   checkUsername = checkUsernameArray[0];
   checkUsername = checkUsername.replace("@", "");
   if(checkPersonOnline(checkUsername))
      output.println(previousInput);
   else
       System.out.println(checkUsername + " is offline, message not sent");
}

public boolean checkPersonOnline(String username){
    boolean check = false;
    output.println("/check "+ username); //send command to check with the username
    try{
        if(serverScannerInput.readLine().equals("true"))
            check = true;
    }catch(IOException ex){
        ex.printStackTrace();
    }
    return check;
}
public boolean checkPersonExists(String username){
    boolean check = false;
    String serverInput;
    try(BufferedReader serverScannerInput = new BufferedReader(new InputStreamReader(userSocket.getInputStream()));
        PrintWriter outputToServer = new PrintWriter(userSocket.getOutputStream(), true);
        ){
        outputToServer.println("/exists "+username);
        serverInput = serverScannerInput.readLine();
        System.out.println("Server responded "+serverInput);
        if(serverInput.equals("true"))
            check = true;
        else
            check = false;
    }catch(IOException ex){
        ex.printStackTrace();
    }
    return check;
}
public void addFriend(String username){
    //OVERVIEW: takes a username, checks if person exists, checks if person is in client's friendsList, adds username to persons friendsList
    //Check if person exists
    if(checkPersonExists(username)){
        //check if person is in friends list. If false: add person to friendsList. If true: display's: "This person is in your friendsList already"
        if(!user.checkFriends(username)){
           output.println("/add" + username );
        }else{
            System.out.println("This person is already in your friends list");
        }
    }else{
        System.out.println(username +" does not exist, please enter new command");
    }        
}

public void removeFriend(String username){
    //Checks if username is in client's friends List, sends remove command to server
    if(user.checkFriends(username))
        output.println("/remove "+username);
    else
        System.out.println(username+ " is not in your friends list, please enter new command");
}

public void createClient(String previousInput){
    System.out.println("createClient method started");        
    try(          
        BufferedReader serverScannerInput = new BufferedReader(new InputStreamReader(userSocket.getInputStream()));
        PrintWriter outputToServer = new PrintWriter(userSocket.getOutputStream(), true);
        ){
        String userInput = previousInput;
        String[] breakUp = userInput.split(" ");
        String serverInput;
        while(breakUp.length != 2){
            System.out.println("Missing argument please re-enter login");
            userInput = scanner.readLine();
            breakUp = userInput.split(" ");
            if(userInput.equals("exit")){ //Re-check to see if you need this
                System.out.println("closing program");
                System.exit(1);
            }
        }
        //Checks if the user exists or not
        if(!this.checkPersonExists(userInput)){
            //Sends commands to create user
            System.out.println("/create sent");
            outputToServer.println("/create " +userInput);
            output.flush();
        }else{
            System.out.println("The name you have entered has already been created please choose another command");
        }
        System.out.println("new user created. Please login");
    }catch(Exception e){
        e.printStackTrace();
    }
}

public void login(String previousInput) {
    try{
    String userInput = previousInput;
    String[] breakUp = userInput.split(" ");
    String serverInput;
    System.out.println("please enter login: \"username password\" ");
    while(breakUp.length != 2){
        System.out.println("Missing argument please re-enter login");
        userInput = scanner.readLine();
        breakUp = userInput.split(" ");
        if(userInput.equals("exit")){ //Re-check to see if you need this
            System.out.println("closing program");
            System.exit(1);
        }
    }
    //Checks if user inputed correct login information(/login command): send user login together and is suppose to recieve "true" or "false" 
    output.println("/exists "+ userInput);
    serverInput = serverScannerInput.readLine();
    while(serverInput.equals(false)){
        //place code for bad login
        System.out.println("Invalid login");
        userInput = scanner.readLine();
        login(userInput);
        serverInput = serverScannerInput.readLine();
    }
    if(serverInput.equals("true")){
        //creates user
        output.println("/login "+ userInput);
        user = new Client(breakUp[0], breakUp[1]);
        //user.changeStatus();
        output.println("/getFriendsList "+ breakUp[0]); //sends getFriendsList plus username
        serverInput = serverScannerInput.readLine();
        breakUp = serverInput.split(" ");
        for(int x = 0; x< breakUp.length; x++){
            instance.addFriend(breakUp[x]);
        }
    }
}catch(IOException ex){
        ex.printStackTrace();
        System.exit(1);
    }
}
}

服务器线程:

package COE528.MajorProject;

import java.net.Socket;
import java.io.*;
import java.net.ServerSocket;


public class ServerThread extends Thread{
private final Socket client;
private final ServerProtocol protocol;  

public ServerThread (Socket clientThread){
    client = clientThread;
    protocol = new ServerProtocol(client);  
}

@Override
public void run(){
    System.out.println("Thread created"); //GET RID OF LATER
    String inputLine=null;
    String[] breakUp;
    try(
            BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter output = new PrintWriter(client.getOutputStream(), true);
            ){
        System.out.println("trying BufferedReader " + input.toString());
        inputLine = input.readLine();
        while(!inputLine.equals("/exit")){
            System.out.println("server recieved :" + inputLine);
            breakUp = inputLine.split(" ");
            if(breakUp[0].equals("/login")){
                protocol.login(breakUp[0]);
            }
            if(breakUp[0].equals("/create")){
                System.out.println("create started");
                StringBuilder foo = new StringBuilder();
                foo.append(breakUp[1]);
                foo.append(breakUp[2]);
                protocol.createClient(foo.toString());
            }
            if(breakUp[0].equals("/exists")){
                protocol.checkForClientExists(breakUp[1]);
            }
            inputLine = input.readLine();
            System.out.println("reading next input: " + inputLine);
        }
        //input.close();
        //output.close();

        //closing of thread
    }catch(IOException ex){

    }
}
}

【问题讨论】:

    标签: java multithreading sockets bufferedreader


    【解决方案1】:

    如果没有自己运行它,我猜这是因为您在 BufferedReaders 上使用了 try-with-resources 循环。当您关闭 BufferedReader 时,您还将关闭底层流,这意味着您的套接字(以及您的连接)将被关闭。

    也许,与其在每个方法调用上为您的输入流打开一个新的BufferedReader 并为您的输出流打开一个新的PrintWriter,也许它们应该在套接字旁边是全局的?要么这样,要么在这种情况下根本不使用 try-with-resources。

    【讨论】:

    • 我会尝试摆脱 try-with-resources,如果这样做/不起作用,我会通知您。
    猜你喜欢
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 2011-12-12
    • 2012-09-30
    • 2011-11-04
    相关资源
    最近更新 更多