How do I make a simple client/server app in two different projects in Eclipse?

时间:2017-06-15 09:46:13

标签: java eclipse server client client-server

I am trying to make a client-server game for school. We have to do two separate porjects in eclipse. One for the client and one for the server. The problem is whenever I try to connect the client to the server I get a java.net.BindException. Saying: Address already in use: JVM_Bind. Can anyone please tell me what to do or what I did wrong? Thank you!

This is my code for the client:

public class SimpleClient {

    private static final int PORT = 2345;

    public static void main(String... args) {
        try(Socket socket = new Socket(InetAddress.getLocalHost(), PORT)) {
            OutputStream out = socket.getOutputStream();
            InputStream in = socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

And this is the code for the server:

public class GameServer implements Runnable {

    private static final int PORT = 2345;

    @Override
    public void run() {
        try(ServerSocket server = new ServerSocket(PORT)) {
            while(true) {
                System.out.println("server ready!");
                Socket client = server.accept();
                System.out.println("welcome friend!");

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String... args) {
        new Thread(new GameServer()).start();
    }
}

0 个答案:

没有答案