• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • About
  • Life
  • Tech
  • Travel
  • Work
  • Questions
  • Contact

Welcome

.

Java socket cannot read from lines

April 10, 2020 by

Questions › Java socket cannot read from lines
0
Vote Up
Vote Down
Garmaine asked 3 years ago

I am trying to make a small login/registration window, but I could not proceed further because my server code cannot read the inputs from my client code. I could get past the point of me entering info for login or registration. Everytime I press Enter, the connection will reset. What have I done wrong in this case?

Here is a portion of what I have in my client code:

public static void main(String args[]) throws Exception {

    // We create a socket
    Socket clientSocket = new Socket("localhost", 3110);
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    String status = "Init";
    while (true) {
        // Prepare request based on previous response's status.
        String req = "";
        if(status == "Init" || status == "Login Failure" || status == "Registration Success" || status == "Registration Failure") {
            req = getInitReqMsg();
            break;
        }
        else if(status == "LoginSuccess") {
            req = getMenuReqMsg();
            break;                   
        }

        // Encrypt and send request.
        req = AES_128.encrypt(req.getBytes()) + "\n";
        outToServer.writeBytes(req);

        // Receive and decrypt response.
        // For now, responses always have the format "[STATUS] [MESSAGE]".
        String res = inFromServer.readLine();
        res = AES_128.decrypt(res.getBytes());

        status = res.split(" ")[0];

        System.out.println(res.substring(res.indexOf(status) + status.length()).trim());
    }
}

public static String getInitReqMsg() {
    System.out.print("Welcome! Please enter a choice: \nType 1 for Login \nType 2 for Registration \n > ");
    int choice = scanner.nextInt();
    scanner.nextLine();

    if(choice == 1) {
        return getLoginReqMsg();
    }
    else if(choice == 2) {
        return getCreateAcctReqMsg();
    }
    else {
        System.out.println("Invalid input.");
        return getInitReqMsg();
    }
} // end of getInitReqMsg

Here is a portion of what I have in my server code:

public static void main(String[] args) throws Exception {
    ServerSocket welcomeSocket = new ServerSocket(3110);
    System.out.println("Login server running on " + welcomeSocket.getLocalSocketAddress());

    Connection connection  = null;
    connection = dbConnector();

    outer: while(true) {
        Socket connectionSocket = welcomeSocket.accept();
        System.out.println("Connected to " + connectionSocket.getInetAddress());
        BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
        loggedInUser = "";

        while(true) {
            String req = inFromClient.readLine();
            System.out.println(req);
            if(req == "") continue outer;
            req = AES_128.decrypt(req.getBytes());

            String[] reqArr = req.split("\t");

            String res = "";
            switch(reqArr[0]) {
                case "Create":
                    res = Registration(reqArr[1], reqArr[2], reqArr[3]);
                break;

                case "Login":
                    res = Login(reqArr[1], reqArr[2]);
                    if(res.contains("Login Success")) {
                        loggedInUser = reqArr[1];
                    }
                break;

                case "Capitalize":
                    res = doCapitalize(reqArr[1]);
                break;

                case "Logout":
                    loggedInUser = "";
                    res = "LogoutSuccess Bye!";
            }

            res = AES_128.encrypt(res.getBytes()) + "\n";
            outToClient.writeBytes(res);
        }
    }
}
Are you looking for the answer?
Original Question and Possible Answers can be found on `http://stackoverflow.com`

Question Tags: bufferedreader, java, sockets

Please login or Register to submit your answer




Primary Sidebar

Tags

Advancements best Business strategies commercial convenience economic Finances Cognitive decline Financial growth firm Future Hidden Gems Home hydration Impact Innovations lighting line of work Mental health Must-See New York City office patronage Productivity profession Profitability tips Profit optimization pursuit recreation Revenue enhancement romance sippy cups social station Technological breakthroughs technology toddlers trading transaction Treasures Uncover undertaking Well-being Wonders Work Young onset dementia

Newsletter

Complete the form below, and we'll send you all the latest news.

Footer

Footer Funnies

Who knew that reading the footer could be such a hilarious adventure? As we navigate websites, books, and documents, we often stumble upon the unassuming space at the bottom, only to discover a treasure trove of amusement. In this side-splitting compilation, we present 100 jokes that celebrate the unsung hero of content – the footer. Get ready to chuckle, giggle, and maybe even snort as we dive into the world of footnotes, disclaimers, and hidden comedic gems. Brace yourself for a wild ride through the footer!

Recent

  • Unveiling the Enigma: Almost-Magical Lamp Lights Highway Turns
  • The Impact of Young Onset Dementia on Employment and Finances: Optimizing Post-Diagnostic Approaches
  • 11 Wonders of 2023 Technological Breakthrough – Unveiling the Future
  • Work from Home and Stay Mentally Sane – Achieve Productivity and Well-being
  • Hidden Gems of New York City – Uncover the Must-See Treasures!

Search

Tags

Advancements best Business strategies commercial convenience economic Finances Cognitive decline Financial growth firm Future Hidden Gems Home hydration Impact Innovations lighting line of work Mental health Must-See New York City office patronage Productivity profession Profitability tips Profit optimization pursuit recreation Revenue enhancement romance sippy cups social station Technological breakthroughs technology toddlers trading transaction Treasures Uncover undertaking Well-being Wonders Work Young onset dementia

Copyright © 2023