Zy0n
Zy0n

Reputation: 785

Connection Refused - Java Client/Server

I'm trying to create a java push server model for testing on my own machine, this won't be used to connect external clients as the server and client will be on the same machine. After the client connects on the port specified by he/she, they should send a message of their choice that will be sent back to them, and any other clients connected to the same port.

The problem I'm having is i receive a java.net.ConnectException: Connection refused: connect when this is attempted. Below is the client and the server.

Edit: I've taken the time to ensure that the necessary ports are open too, and even disabled my firewall, but to no avail.

Server:

class MainServer {
    // port that oir server is going to operate on
    final static int port = 1234;
    public static void main(String[] args) {
        // this is going to model the server for the moment
        System.out.println("Server has been started...");
        Buffer<Messages> store = new Buffer<Messages>(10);
        new Writer(store).start();
        try {
            ServerSocket serve = new ServerSocket(port);
            while(true) {
                // wait for server request
                Socket socket = serve.accept();
                // start thread to service request
                new ServerThread(socket,store).start();
            }
        } catch(IOException e) {e.printStackTrace();}
    }
}

class ServerThread extends Thread {
    Socket socket;
    Buffer<Messages> buffer;

    public ServerThread(Socket s, Buffer<Messages> b) {
        socket = s;buffer = b;
    }

    public void run() {
        try {
            DataInputStream in = new DataInputStream(socket.getInputStream());
            int port = in.readInt();
            System.out.println("Port: "+port);
            Messages ms = new Messages(port);
            // Read message as string from user
            String message = in.readUTF();
            int k = in.readInt();

            while(k != -1) {
                // Add message to array
                // read next message
                ms.add(message);
                message = in.readUTF();
            }
            // close connection
            socket.close();
            // add message to buffer
            buffer.put(ms);

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

class Writer extends Thread {
    Buffer<Messages> buffer;

    public Writer(Buffer<Messages> m) {buffer = m;}

    public void run() {
        while(true) {
            Messages dp = buffer.get();
            dp.write();
        }
    }
}

class Buffer <E> {
    /**
     * Producer & Consumer Buffer
     */

    private int max;
    private int size = 0;
    private ArrayList<E> buffer;
    private Semaphore empty; //control consumer
    private Semaphore full; // control producer
    private Lock lock = new ReentrantLock();

    public Buffer(int s) {
        buffer = new ArrayList<E>();
        max = s;
        empty = new Semaphore(0);
        full = new Semaphore(max);
    }

    // add data to our array
    public void put(E x) {
        try {
            full.acquire();
        } catch(InterruptedException e) {}
        // sync update to buffer
        lock.lock();
        try {
            buffer.add(x);
            size++;
            empty.release();
        } finally {lock.unlock();}
    }

    public E get() {
        try {
            empty.acquire();
        } catch(InterruptedException e) {}
        // sync uodate on buffer
        lock.lock();
        try {
            E temp = buffer.get(0);
            buffer.remove(0);
            size--;
            full.release();
            return temp;
        } finally {lock.unlock();}
    }
}

final class Messages {

    private final int port;
    private final ArrayList<String> data = new ArrayList<String>();

    public Messages(int p) {port = p;}
    void add(String message) {
        data.add(message);
    }
    void write() {
        try {

            Socket socket;
            socket = new Socket(InetAddress.getLocalHost(),port);
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            // write message
            out.write(data.size());

            for(String k : data) {out.writeUTF(k);}
            out.flush();
            socket.close();
        } catch(IOException e) {e.printStackTrace();}
    }
}

Client:

class Client {

    final static int nPort = 1234;
    static int serverPort;

    public static void main(String[] args) {
        // this class and those present in it
        // will model the client for assignment 8
        Scanner in = new Scanner(System.in);

        System.out.println("Please enter the messageboard number: ");
        serverPort = in.nextInt();


        System.out.println("Please type your message: ");
        String msg = in.next();
        Listener lis = new Listener(serverPort);
        lis.start();
        boolean go = true;

        while(go) {
            try {
                Thread.sleep(2000);
            } catch(InterruptedException e) {}
            write(serverPort, msg);
            System.out.println("Continue: 0/1");
            int x = in.nextInt();
            if(x == 0)go = false; 
        }
        System.exit(0);
    }

    static void write(int port, String msg) {
        try {

            Socket socket;
            socket = new Socket(InetAddress.getLocalHost(),port);
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            // send message to port
            out.writeInt(port);
            out.writeUTF(msg);
            // write sentinal after message has been written and close socket
            out.writeInt(-1);
            out.flush();
            socket.close();
        } catch(IOException e) {System.out.println(e);}
    }
}

class Listener extends Thread {

    private int port;
    volatile boolean go;

    public Listener(int p) {p = port;}

    public void run() {

        try {
            ServerSocket serversock = new ServerSocket(port);
            while(go) {
                Socket socket = serversock.accept();
                DataInputStream in = new DataInputStream(socket.getInputStream());
                // Read the message
                while(in.available() > 0) {
                    String k = in.readUTF();
                    System.out.print(k+" ");
                }
                System.out.println();
                socket.close();
            }
        } catch(IOException e) {go = false;}
    }
}

Upvotes: 0

Views: 313

Answers (3)

Zy0n
Zy0n

Reputation: 785

Turns out i had a wrong assignment in my Listener class. I had p = port instead of port = p.

Solved. Through my own stupidity.

Upvotes: 1

Saad
Saad

Reputation: 68

Try changing

            socket = new Socket(InetAddress.getLocalHost(),port);
to

            socket = new Socket(*IP OF SERVER (127.0.0.1 if same machine)*, port);

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533660

The hostname you are connecting to is localhost so you are assuming the server is on the same machine. If you need to connect to a different machine, you need to specify the host you want it to connect to.

Upvotes: 0

Related Questions