将客户端应用程序连接到我用Java制造的服务器

时间:2019-03-23 21:14:48

标签: java sockets

几天前,我们在uni做了一个简单的客户端服务器应用程序。该应用程序允许您从服务器请求信息并获得响应。我们在自己的机器(本地主机)上对其进行了测试,并在本地网络中对其进行了测试。一切正常,我们能够将信息从一台计算机发送到本地网络中的另一台计算机。我想在家中使用该应用程序并与朋友交流。我们遇到的问题是,我们无法彼此连接,并且总是收到连接超时错误。

到目前为止,我们已经尝试了不同的方法:

  • 禁用防火墙
    • 在防火墙中授予对Java的权限
    • 尝试了不同的端口
    • 尝试了不同的客户端-服务器应用程序,这些应用程序给了我们完全相同的问题
    • 完全更改了网络(通过不同的路由器连接) 我们正在使用外部IP(而不是本地IP),并且能够ping通彼此的地址。

这是服务器的代码:


public class ServermultifilarTCP1 extends Thread {           
    private Scanner scanTCP;
    private PrintStream printTCP;
    private Socket socketTCP;
    private static Orar orar = new Orar();

    public ServermultifilarTCP1(Socket conexiuneTCP) throws IOException {
        this.socketTCP = conexiuneTCP;        // Obtinere socket
        this.scanTCP = new Scanner(socketTCP.getInputStream());
        this.printTCP = new PrintStream(socketTCP.getOutputStream());
    }

    public void run() {
        String mesaj;
        int zi;

        try {
             while(true) {
                if (scanTCP.hasNextLine()) {
                    mesaj = scanTCP.nextLine();
                    if (mesaj.equals("getOrar")) {
                        try {
                            zi = Integer.parseInt(scanTCP.nextLine());
                            String rezultat = orar.getOrar(zi);
                            printTCP.println(rezultat);
                        } catch (NumberFormatException ex) {
                            printTCP.println("Stop");
                            break;
                        }
                    }
                }
            }
            socketTCP.close();    // Inchiderea socketului si a fluxurilor
            JOptionPane.showMessageDialog(null, "Server: Bye!");
        } catch (IOException ex) {  ex.printStackTrace();   }
    }

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

        int portTCP = Integer.parseInt(JOptionPane.showInputDialog(

                         "Server: introduceti numarul de port al serverului"));

        ServerSocket serverTCP = new ServerSocket(portTCP); // Creare socket server

        while (true) {

            Socket conexiune = serverTCP.accept();

            ServermultifilarTCP1 server = new ServermultifilarTCP1(conexiune);

            server.start();

        }

    }

}

这是Client类:

package pachetorar;



import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.net.*;

import java.io.*;

import java.util.*;



public class ClientTCP1 {

    private Scanner scanTCP;

    private PrintStream printTCP;

    private Socket socketTCP;

    private int portTCP;

    private InetAddress adresaIP;

    private JFrame frame;



    public ClientTCP1() throws IOException {     

        this.portTCP = Integer.parseInt(JOptionPane.showInputDialog(

                       "Client: introduceti numarul de port al serverului"));

        this.adresaIP = InetAddress.getByName(JOptionPane.showInputDialog(

                       "Client: introduceti adresa serverului"));

        this.socketTCP = new Socket(adresaIP, portTCP);        // Creare socket

        this.scanTCP = new Scanner(socketTCP.getInputStream());

        this.printTCP = new PrintStream(socketTCP.getOutputStream());



        JFrame frame = new JFrame("Client TCP");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container containerCurent = frame.getContentPane();

        containerCurent.setLayout(new BorderLayout());



        JPanel pane = new JPanel(new GridLayout(0, 1));

        final JLabel eticheta = new JLabel("Orarul zilei de:");

        pane.add(eticheta);



        final int numButtons = 8;

        final JRadioButton[] radioButtons = new JRadioButton[numButtons];

        final ButtonGroup group = new ButtonGroup();



        radioButtons[0] = new JRadioButton("Luni");

        radioButtons[0].setActionCommand("0");

        radioButtons[1] = new JRadioButton("Marti");

        radioButtons[1].setActionCommand("1");

        radioButtons[2] = new JRadioButton("Miercuri");

        radioButtons[2].setActionCommand("2");

        radioButtons[3] = new JRadioButton("Joi");

        radioButtons[3].setActionCommand("3");

        radioButtons[4] = new JRadioButton("Vineri");

        radioButtons[4].setActionCommand("4");

        radioButtons[5] = new JRadioButton("Sambata");

        radioButtons[5].setActionCommand("5");

        radioButtons[6] = new JRadioButton("Duminica");

        radioButtons[6].setActionCommand("6");

        radioButtons[7] = new JRadioButton("Stop");

        radioButtons[7].setActionCommand("Stop");

        radioButtons[0].setSelected(true);



        for (int i = 0; i < numButtons; i++) {

            group.add(radioButtons[i]);

            pane.add(radioButtons[i]);

        }

        containerCurent.add(pane, BorderLayout.WEST);



        JButton sendButton = new JButton("Trimite");



        sendButton.addActionListener(new ActionListener() {

            // trimiterea catre server a cererii de efectuare a serviciului

            public void actionPerformed(ActionEvent e) {

                String service = "getOrar";

                printTCP.println(service);

                String command = group.getSelection().getActionCommand();

                printTCP.println(command);

            }

        });

        containerCurent.add(sendButton, BorderLayout.NORTH);



        final JTextArea outGrafic = new JTextArea(8, 40); // Zona non-editabila

        JScrollPane scrollPane = new JScrollPane(outGrafic,

                     JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

                     JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        outGrafic.setEditable(false);

        containerCurent.add(outGrafic, BorderLayout.CENTER);

        frame.pack(); frame.setVisible(true);



        String mesaj;

        while(true) {                     // afisarea raspunsului primit de la server

            if (scanTCP.hasNextLine()) {

                mesaj = scanTCP.nextLine();

                outGrafic.setText(outGrafic.getText() + mesaj + "\n");

                if (mesaj.equals("Stop")) System.exit(0);  // Conditie oprire

            }

        }

    }

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

        ClientTCP1 client = new ClientTCP1();

    }
}

这是服务器类使用的类,但与我认为的问题无关:

package pachetorar; public class Orar {

    private String[] orar; // camp ascuns (starea obiectului)



    public Orar() {

        orar = new String[7]; // alocarea dinamica a spatiului pentru tablou

        // popularea tabloului cu valori

        orar[0] = "Luni este curs TPI la seriile D si E " +

                                "si laborator TPI la seria E.";

        orar[1] = "Marti nu sunt ore de TPI.";

        orar[2] = "Miercuri este laborator TPI la seriile D si E.";

        orar[3] = "Joi este laborator TPI la seria D.";

        orar[4] = "Vineri este laborator TPI la seria D.";

        orar[5] = "Sambata nu sunt ore de TPI.";

        orar[6] = "Duminica nu sunt ore de TPI.";

    }

    public String getOrar(int zi) { // metoda accesor - getter

        return orar[zi];            // returneaza un element al tabloului

    }

    public void setOrar(int zi, String text) { // metoda accesor - setter

        orar[zi] = text;                       // inlocuieste un element

    }

}

期望的结果应该是在两台计算机之间建立连接,而不会出现连接超时错误。如果客户端无法与服务器通信,则gui将不会显示,并且我会收到上述错误。

谢谢您的帮助!

2 个答案:

答案 0 :(得分:0)

由于您的计算机位于NAT之后,因此您无法直接访问朋友的计算机。您应该使用Network address translator traversalport forwarding。或两台PC应该在同一物理网络中(也可以使用VPN)。

答案 1 :(得分:0)

您很可能需要打开端口,然后在路由器的设置中转发端口。这是告诉路由器,您选择使用的端口上出现的任何连接都应重定向到您的计算机。

例如,如果我要打开端口x,然后将其转发到计算机的本地IP地址,则使用端口x到我的公共IP的任何入站连接都将重定向到计算机上该端口上运行的应用程序。