Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Java Help with server

aitía

Coder
I have many errors in my java program that I need help fixing. It is a server that another program which is the client connects to, but exceptions are being thrown.

error: unreported exception IOException; must be caught or declared to be thrown

Code:
import java.net.*;
import java.io.*;

public class GreetServer {
    private ServerSocket serverSocket;
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;

    public void start(int port) {
        serverSocket = new ServerSocket(port);
        clientSocket = serverSocket.accept();
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String greeting = in.readLine();
            if ("hello server".equals(greeting)) {
                out.println("hello client");
            }
            else {
                out.println("unrecognised greeting");
            }
    }

    public void stop() {
        in.close();
        out.close();
        clientSocket.close();
        serverSocket.close();
    }
    public static void main(String[] args) {
        GreetServer server=new GreetServer();
        server.start(6666);
    }
}
 
If you have no idea why you are getting these errors, it is absolutely essential that you read up on exceptions, and fully understand how Java handles them. And also consult the JavaDocs on any function you call, such as ServerSocket(). You can't be a Java programmer without doing that.
 
I have many errors in my java program that I need help fixing. It is a server that another program which is the client connects to, but exceptions are being thrown.

error: unreported exception IOException; must be caught or declared to be thrown

Code:
import java.net.*;
import java.io.*;

public class GreetServer {
    private ServerSocket serverSocket;
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;

    public void start(int port) {
        serverSocket = new ServerSocket(port);
        clientSocket = serverSocket.accept();
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String greeting = in.readLine();
            if ("hello server".equals(greeting)) {
                out.println("hello client");
            }
            else {
                out.println("unrecognised greeting");
            }
    }

    public void stop() {
        in.close();
        out.close();
        clientSocket.close();
        serverSocket.close();
    }
    public static void main(String[] args) {
        GreetServer server=new GreetServer();
        server.start(6666);
    }
}
Hi there,

IOExceptions usually mean you are trying to do something with input/output.. Check if you are reading/writing to files correctly
 
Hi there,

IOExceptions usually mean you are trying to do something with input/output.. Check if you are reading/writing to files correctly
Yes indeed. First of all though, check the stack trace for the precise error and location. Why didn't you post that ?
 
I read that ServerSocket is the method which waits for requests to come in over the network then performs some operation based on that request. Below is my trace I am trying to fix.

Code:
GreetClient.java:2: error: cannot find symbol
    private Socket clientSocket;
            ^
  symbol:   class Socket
  location: class GreetClient
GreetClient.java:3: error: cannot find symbol
    private PrintWriter out;
            ^
  symbol:   class PrintWriter
  location: class GreetClient
GreetClient.java:4: error: cannot find symbol
    private BufferedReader in;
            ^
  symbol:   class BufferedReader
  location: class GreetClient
GreetClient.java:7: error: cannot find symbol
        clientSocket = new Socket(ip, port);
                           ^
  symbol:   class Socket
  location: class GreetClient
GreetClient.java:8: error: cannot find symbol
        out = new PrintWriter(clientSocket.getOutputStream(), true);
                  ^
  symbol:   class PrintWriter
  location: class GreetClient
GreetClient.java:9: error: cannot find symbol
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                 ^
  symbol:   class BufferedReader
  location: class GreetClient
GreetClient.java:9: error: cannot find symbol
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                                    ^
  symbol:   class InputStreamReader
  location: class GreetClient
7 errors
 
I read that ServerSocket is the method which waits for requests to come in over the network then performs some operation based on that request. Below is my trace I am trying to fix.

Code:
GreetClient.java:2: error: cannot find symbol
    private Socket clientSocket;
            ^
  symbol:   class Socket
  location: class GreetClient
GreetClient.java:3: error: cannot find symbol
    private PrintWriter out;
            ^
  symbol:   class PrintWriter
  location: class GreetClient
GreetClient.java:4: error: cannot find symbol
    private BufferedReader in;
            ^
  symbol:   class BufferedReader
  location: class GreetClient
GreetClient.java:7: error: cannot find symbol
        clientSocket = new Socket(ip, port);
                           ^
  symbol:   class Socket
  location: class GreetClient
GreetClient.java:8: error: cannot find symbol
        out = new PrintWriter(clientSocket.getOutputStream(), true);
                  ^
  symbol:   class PrintWriter
  location: class GreetClient
GreetClient.java:9: error: cannot find symbol
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                 ^
  symbol:   class BufferedReader
  location: class GreetClient
GreetClient.java:9: error: cannot find symbol
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                                    ^
  symbol:   class InputStreamReader
  location: class GreetClient
7 errors
Are you sure you are importing those classes correctly?
 
This is not a stack trace, but compiler output. But it's old output, the code you posted doesn't produce these errors, you had apparently already resolved these errors by adding the correct imports. The only errors reported now are about exceptions. Please don't waste anybody's (and your own) time by being imprecise. Programming is an exact science.

Now you need to read up on Java exceptions and learn that you either need to catch or declare them in your code (actually the compiler says so quite clearly).
 
Thanks to your feedback I was able to fix the above code, now the issue I am having is with my code for the client. I have pasted it below, specifically I receive the output "Error missing return statement" and I am wondering if I need to create a main method and also I am not sure what will be required within it according to what I have already defined in my class.

Java:
public class GreetClient
{
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;
    public void startConnection(String ip, int port)
    {
        try
        {
            clientSocket = new Socket(ip, port);
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        }
        catch (Exception ex)
        {
            System.out.print(ex.toString());
        }
    }
    
    public String sendMessage(String msg)
    {
        try
        {
            out.println(msg);
            String resp = in.readLine();
            return resp;
        }
        catch (Exception ex)
        {
            System.out.print(ex.toString());
        }
    }

    public void stopConnection() 
    {
        try
        {
            in.close();
            out.close();
            clientSocket.close();
        }
        catch (Exception ex) 
        {
            System.out.print(ex.toString());
        }
     }
}
 
Last edited by a moderator:
Why don't you post complete code (it didn't compile due to missing imports), and post the compiler output verbatim ?Had you looked properly at the compiler message you'd have seen the line number, and that it's is not about whether or not having a main() function. It is about function sendMessage() not returning a value from the try code branch.

It is not required to have a main() method in any Java class, but if you want to use this code as a client program, as I think you do, you'll need one.
 
Last edited by a moderator:
@cbreemer I no longer received errors, my program compiles although nothing is displayed in the command prompt after I run the program along side my server program; I can paste my server code later also since I wish to know why they are not connecting with each other. Can you tell me if this is better, my changes are the ones you recommended which was to add a return statement within sendMessage() and to add a main method.

Code:
import java.net.*;
import java.io.*;

public class GreetClient {
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;
    public void startConnection(String ip, int port) {
        try {
        clientSocket = new Socket(ip, port);
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        } catch (Exception ex) {
            System.out.print(ex.toString());
        }
    }
    public String sendMessage(String msg) {
    try {
        out.println(msg);
        String resp = in.readLine();
        return resp;
    } catch (Exception ex) {
        System.out.print(ex.toString());
    }
    return msg;
    }
    public void stopConnection() {
    try {
        in.close();
        out.close();
        clientSocket.close();
    } catch (Exception ex) {
        System.out.print(ex.toString());
    }
  }
  public static void main(String[] args) {
    GreetClient server=new GreetClient();
  }
}
 
Thanks to your feedback I was able to fix the above code, now the issue I am having is with my code for the client. I have pasted it below, specifically I receive the output "Error missing return statement" and I am wondering if I need to create a main method and also I am not sure what will be required within it according to what I have already defined in my class.

Java:
public class GreetClient
{
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;
    public void startConnection(String ip, int port)
    {
        try
        {
            clientSocket = new Socket(ip, port);
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        }
        catch (Exception ex)
        {
            System.out.print(ex.toString());
        }
    }
  
    public String sendMessage(String msg)
    {
        try
        {
            out.println(msg);
            String resp = in.readLine();
            return resp;
        }
        catch (Exception ex)
        {
            System.out.print(ex.toString());
        }
    }

    public void stopConnection()
    {
        try
        {
            in.close();
            out.close();
            clientSocket.close();
        }
        catch (Exception ex)
        {
            System.out.print(ex.toString());
        }
     }
}
So I took the liberty of formatting your code just a bit, so things are a bit more readable and clearer. Your issue is here
1669516641628.png

Can you take a guess as to why this method would be causing the "no return statement" error? :)
HINT: What would happen if your method crashes inside of that try-block?
 
Apart from the poor indentation, that is a fine bit of Java code, nothing wrong with it. Although I would personally return a different string from the catch branch (such as the exception message) rather than just returning the input string.

But why do you think this code should be doing something ? All you do is call the default constructor, which does not do anything except create the GreetClient object (which curiously has the name server). And then you exit without even referencing your object. Sure you have the methods there to get something going, but nobody is calling them.
 
@cbreemer Do you suggest I write something similar to return "Connecting";? I think it should say a message when it has successfully connected and when it disconnects from the server. I have pasted my server code below now, one line I would like to understand more is the if ("hello server".equals(greeting)). How do I reference my object when I exit in stopConnection(), is it with the GreetClient object also or maybe I should pass it under the parenthesis of close(). @Antero360 If my method crashes then nothing would be shown other than the console's specific error.

Code:
import java.net.*;
import java.io.*;

public class GreetServer {
    private ServerSocket serverSocket;
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;
    public void start(int port) {
        try {
        serverSocket = new ServerSocket(port);
        clientSocket = serverSocket.accept();
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String greeting = in.readLine();
            if ("hello server".equals(greeting)) {
                out.println("hello client");
            }
            else {
                out.println("unrecognised greeting");
            }
        } catch(IOException ex){
            System.out.println (ex.toString());
        }
    }
    public static void main(String[] args) {
        GreetServer server=new GreetServer();
        server.start(6666);
    }
}
 
@cbreemer I no longer received errors, my program compiles although nothing is displayed in the command prompt after I run the program along side my server program; I can paste my server code later also since I wish to know why they are not connecting with each other. Can you tell me if this is better, my changes are the ones you recommended which was to add a return statement within sendMessage() and to add a main method.

Code:
import java.net.*;
import java.io.*;

public class GreetClient {
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;
    public void startConnection(String ip, int port) {
        try {
        clientSocket = new Socket(ip, port);
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        } catch (Exception ex) {
            System.out.print(ex.toString());
        }
    }
    public String sendMessage(String msg) {
    try {
        out.println(msg);
        String resp = in.readLine();
        return resp;
    } catch (Exception ex) {
        System.out.print(ex.toString());
    }
    return msg;
    }
    public void stopConnection() {
    try {
        in.close();
        out.close();
        clientSocket.close();
    } catch (Exception ex) {
        System.out.print(ex.toString());
    }
  }
  public static void main(String[] args) {
    GreetClient server=new GreetClient();
  }
}

Java:
public String sendMessage(String msg)
{
    String resp = "";
    try
    {
        out.println(msg);
        resp = in.readLine();
    }
    catch (Exception ex)
    {
        //resp = ex.toString();
        System.out.print(ex.toString());
    }

    return resp;
}

This should help you with readability. Also lol, the reason why I asked that particular question, was to put more focus on that SendMessage method. Basically, hinting at the issue, without actually saying what the issue really is :) I tend to do that a lot as I help out...
1) It keeps focus on the possible cause of the issue
2) It helps you as the coder, get better at debugging, rather than being given the answer from the jump (a very unpopular methodology among some, but I found that more often than not it helps the user grow as a developer...talking from experience lol)
3) Familiarizes the user with the concept of "rubber duck debugging"
 
Last edited:
@aitía
Why are you now bringing up the server again ? We were discussing the client and why it does not do anything. Sure, the server code will need some work but for now it's doing its job, which is listening on port 6666. Don't worry about the details just now. Your first task is to get a connection between client and server.
Is it clear to you why the client and server parts are not connecting to each other, as you seem to have expected, and what basic steps must be done in the client to get something going ?
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom