连接被拒绝 - Java客户端/服务器

时间:2014-12-14 19:25:59

标签: java multithreading concurrency client-server

我正在尝试创建一个java推送服务器模型,用于在我自己的机器上进行测试,这不会用于连接外部客户端,因为服务器和客户端将在同一台机器上。客户端在他/她指定的端口上连接后,他们应该发送一个他们选择的消息,这些消息将被发送回给他们,以及连接到同一端口的任何其他客户端。

我遇到的问题是在尝试此操作时收到java.net.ConnectException: Connection refused: connect。以下是客户端和服务器。

编辑:我花时间确保必要的端口也是打开的,甚至禁用了我的防火墙,但无济于事。

服务器:

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();}
    }
}

客户端:

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;}
    }
}

3 个答案:

答案 0 :(得分:1)

原来我的Listener课程中的分配错误了。我有p = port而不是port = p

解决。通过我自己的愚蠢。

答案 1 :(得分:0)

您要连接的主机名是localhost,因此您假设服务器位于同一台计算机上。如果需要连接到其他计算机,则需要指定要连接到的主机。

答案 2 :(得分:0)

尝试更改

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

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