客户&服务器未通过本地网络连接

时间:2016-04-16 21:19:47

标签: java sockets networking serversocket

我试图连接我的服务器应用程序和客户端应用程序,一个在我的计算机(主机)上另一个在我的客户计算机(客户端)上当我在我的计算机上测试我的应用程序时,一切都正常连接并发送消息等但是当我为我的客人计算机启动JAR文件,它将无法连接它只会关闭流...在wifi配置等环境中,我有什么关键吗?这是我的第一个Socket应用程序,所以我显然不是这方面的专家,但如果你能指出我正确的方向或指出问题,那将是非常感谢。

主持人:

    public class EchoClient {

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

            String serverIP = InetAddress.getLocalHost().getHostAddress();
            System.out.println(serverIP);

            EchoRun er = new EchoRun(serverIP);
            er.startRunning();

        }

    }
    public class Echo extends JFrame implements ActionListener {

        private ObjectOutputStream output;
        private ObjectInputStream input;
        private Socket socket;
        private JTextField userText;
        private JTextArea chatWindow;
        private ServerSocket server;
        private ServerSocket server2;
        private Socket connection;
        private Socket connection2;

        public Echo() {
            super(" Echo Server");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(500, 500);
            System.out.println("Server Started");
            userText = new JTextField();

            userText.setEditable(false);
            chatWindow = new JTextArea();
            userText.addActionListener(
                    new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    sendMessage(e.getActionCommand());
                    userText.setText(" ");
                }
            });
            add(userText, BorderLayout.SOUTH);
            add(new JScrollPane(chatWindow));
            add(chatWindow, BorderLayout.CENTER);
            setVisible(true);
        }
    // let user tyope in the jtextarea

        public void startRunning() {
            try {
                server = new ServerSocket(2014, 100);

                while (true) {
                    try {
                        // will start seperate thread for downloading voice file
                        Thread dow = new Thread(new downloadVoiceFile());
                        dow.start();




                          Thread fileListener = new Thread(new fileListener());
                          fileListener.start();

                        waitForConnection();
                        setUpStreams();
                        whileChatting();

                    } catch (EOFException eofExcption) {
                        showMessage("\n Server Offline");
                    } finally {
                        close();
                    }

                }

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

        }

        private void waitForConnection() throws IOException {

            showMessage("\nWaiting For Clients");
            connection = server.accept();
            showMessage(" Now Connected To " + connection.getInetAddress().getHostName());

        }

        private void setUpStreams() throws IOException {

            output = new ObjectOutputStream(connection.getOutputStream());
            output.flush();
            input = new ObjectInputStream(connection.getInputStream());
            showMessage("\n Streams Established");

        }

        private void whileChatting() throws IOException {
            String message = "\nYou Are Now Connected";
            sendMessage(message);

            ableToType(true);

            do {
                try {

                    message = (String) input.readObject();
                    showMessage("\n" + message);

                } catch (ClassNotFoundException classNotFoundException) {
                    showMessage("\n Unknown Error ");
                }

            } while (!message.equals("CLIENT END"));
        }

        private void close() {
            showMessage("\n Closing Connections");
            ableToType(false);
            try {
                output.close();
                input.close();
                connection.close();

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

        private void sendMessage(String message) {
            try {
                output.writeObject("Server -" + message);
                output.flush();
                showMessage("\n SERVER -" + message);

            } catch (IOException ioException) {
                chatWindow.append("Cannot Send That Message try AGain");
            }

        }

        private void showMessage(final String text) {
            SwingUtilities.invokeLater(
                    new Runnable() {
                @Override
                public void run() {
                    chatWindow.append(text);

                }

            }
            );

        }

        public void ableToType(final boolean tof) {
            SwingUtilities.invokeLater(
                    new Runnable() {
                @Override
                public void run() {
                    userText.setEditable(tof);
                }

            }
            );
        }

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

            Echo echo = new Echo();
            echo.startRunning();

        }

        public void downloadVoiceFile() throws IOException {

            System.out.println("hello from download");
            Thread dow = new Thread(new downloadVoiceFile());
            dow.start();

        }

        @Override
        public void actionPerformed(ActionEvent e) {

        }
    }




CLIENT: 


public class EchoRun extends JFrame implements ActionListener, KeyListener, Runnable {

    /*
    Audio Vars

     */
    String voiceOutput = "output.wav";
    TargetDataLine line;
    double duration, seconds;
    AudioInputStream audioInputStream;
    /*
    Send File VARS

     */

    private final int BUFFER_SIZE = 128000;
    private File soundFile;
    private AudioInputStream audioStream;
    private AudioFormat audioFormat;
    private SourceDataLine sourceLine;
/*
    App VARS main
    */
    private JButton file, mic;
    String errStr;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private Socket socket;
    private JTextField userText;
    private JTextArea chatWindow;
    private ServerSocket server;
    private Socket connection;
    private Socket connection2;
    private Socket connection3;

    private String message = "";
    private String serverIP;
    Thread thread;
    JToolBar toolbar;

    public EchoRun(String host) {
        super(" Echo Client");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 500);
        setLookAndFeel();
        System.out.println("Server Started");
        userText = new JTextField();
        userText.setEditable(false);
        chatWindow = new JTextArea();
        mic = new JButton("Microphone");
        mic.setFont(new Font("Serif", Font.BOLD, 14));
        mic.setForeground(Color.blue);
        userText.addKeyListener(this);

        file = new JButton("Send File");
        file.addActionListener(this);
        file.setFont(new Font("Serif", Font.BOLD, 14));
        file.setForeground(Color.blue);
        toolbar = new JToolBar();
        toolbar.add(mic);
        toolbar.addSeparator();
        toolbar.add(file);
        toolbar.addSeparator();
        serverIP = host;
        userText.addActionListener(
                new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    sendMessage(e.getActionCommand());
                } catch (IOException ex) {
                    Logger.getLogger(EchoClient.class.getName()).log(Level.SEVERE, null, ex);
                }
                userText.setText(" ");
            }
        });

        add(userText, BorderLayout.SOUTH);
        add(new JScrollPane(chatWindow));
        add(chatWindow, BorderLayout.CENTER);
        add("North", toolbar);
        setVisible(true);
    }

    private void setLookAndFeel() {
        try {
            UIManager.setLookAndFeel("UIManager.getSystemLookAndFeelClassName");
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
                UnsupportedLookAndFeelException e) {
        }
    }

    public void startRunning() throws IOException {
        try {
            connectToServer();
            setUpStreams();
            whileChatting();
        } catch (EOFException eofException) {
            showMessage("Client Terminated Connection");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            closeAll();
        }

    }

    /*
    Connect to server
     */
    private void connectToServer() throws IOException {
        // connect to text to text
        showMessage("\nAttempting To Connect To Server For Main Chat");
        connection = new Socket(InetAddress.getByName(serverIP), 2014);
        showMessage("\nconnected to:" + connection.getInetAddress().getHostName());

    }

    private void setUpStreams() throws IOException {
        output = new ObjectOutputStream(connection.getOutputStream());
        output.flush();
        input = new ObjectInputStream(connection.getInputStream());
        showMessage("\nStreams Established");
    }

    private void whileChatting() throws IOException {
        ableToType(true);
        do {
            try {
                message = (String) input.readObject();
                showMessage("\n" + message);
            } catch (ClassNotFoundException classNotFoundException) {
                showMessage("\n ERROR SENDING OBJECT");

            }
        } while (!message.equals("SERVER - END"));

    }

    private void closeAll() throws IOException {
        showMessage("\n closing...");
        ableToType(false);
        try {
            output.close();
            input.close();
            connection.close();

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

    }

    private void sendMessage(String message) throws IOException {
        try {
            output.writeObject("\nCLIENT - " + message);
            output.flush();
            showMessage("\n Client - " + message);
        } catch (IOException ioException) {
            chatWindow.append("\n ERROR Sending Message");
            ioException.printStackTrace();
        }

    }

    private void showMessage(final String m) {
        SwingUtilities.invokeLater(
                new Runnable() {
            public void run() {
                chatWindow.append(m);
            }
        });

    }

    private void ableToType(final boolean tof) {
        SwingUtilities.invokeLater(
                new Runnable() {
            public void run() {
                userText.setEditable(tof);
            }
        });

    }

    /*
    Handling the microphone
     */
    public void stop() {
        thread = null;
    }

    public void shutDown(String message) {
        if ((errStr = message) != null && thread != null) {
            thread = null;
            System.err.println(errStr);
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyChar() == 'q') {

            System.out.println("Started Recording");
            start();

        }
    }

    public void start() {
        errStr = null;
        thread = new Thread((Runnable) this);
        thread.setName("Capture");
        thread.start();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        Object source = e.getSource();

        if (e.getKeyChar() == 'q') {
            System.out.println("Stopped Recording");
            stop();
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (source == file) {
            try {
                chooseFile();
            } catch (IOException ex) {
                Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /*
    Choose file method
     */
    public void chooseFile() throws IOException {
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Send File");
        fc.setMultiSelectionEnabled(true);
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int dialog = fc.showSaveDialog(this);
        if (dialog == JFileChooser.APPROVE_OPTION) {
            File inputFile = fc.getSelectedFile();
            inputFile.getName();
            inputFile.getAbsoluteFile();
            String nameOf = inputFile.getName();
            System.out.println(" File: " + inputFile);

            sendFile(inputFile);

        }

    }

    public void sendFile(File inputFile) throws IOException {

        connection3 = new Socket(InetAddress.getByName(serverIP), 1991);
        System.out.println("File Being Sent");
        OutputStream output2 = new ObjectOutputStream(connection3.getOutputStream());
        output2.flush();
        InputStream input2 = new ObjectInputStream(connection3.getInputStream());
        System.out.println(input2);

        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(connection3.getOutputStream());
        } catch (IOException ex1) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex1);
            System.out.println("error creating data input stream ");
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(inputFile);

        } catch (FileNotFoundException ex1) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex1);
            System.out.println("error in creating file input stream");

        }

        int count = 0;
        byte[] buffer = new byte[4096];

        try {
            while ((count = fis.read(buffer)) > 0) {
                dos.write(buffer, 0, count);
                dos.flush();
                System.out.println(fis);
            }
        } catch (IOException ex1) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex1);
            System.out.println("error in loop writing");
        }

        try {

            fis.close();
        } catch (IOException ex1) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex1);
            System.out.println("error closing fis");
        }
        try {
            dos.flush();
            dos.close();

        } catch (IOException ex1) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex1);
            System.out.println("or closing dos");
        }

    }

    public void run() {

        duration = 0;
        audioInputStream = null;

        // define the required attributes for our line,
        // and make sure a compatible line is supported.
        AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
        float rate = 44100.0f;
        int channels = 2;
        int frameSize = 4;
        int sampleSize = 16;
        boolean bigEndian = true;

        AudioFormat format = new AudioFormat(encoding, rate, sampleSize, channels, (sampleSize / 8) * channels, rate, bigEndian);

        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

        if (!AudioSystem.isLineSupported(info)) {
            shutDown("Line matching " + info + " not supported.");
            return;
        }

        // get and open the target data line for capture.
        try {
            line = (TargetDataLine) AudioSystem.getLine(info);
            line.open(format, line.getBufferSize());
        } catch (LineUnavailableException ex) {
            shutDown("Unable to open the line: " + ex);
            return;
        } catch (SecurityException ex) {
            shutDown(ex.toString());
            //JavaSound.showInfoDialog();
            return;
        } catch (Exception ex) {
            shutDown(ex.toString());
            return;
        }

        // play back the captured audio data
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int frameSizeInBytes = format.getFrameSize();
        int bufferLengthInFrames = line.getBufferSize() / 8;
        int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
        byte[] data = new byte[bufferLengthInBytes];
        int numBytesRead;

        line.start();

        while (thread != null) {
            if ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
                break;
            }
            out.write(data, 0, numBytesRead);
        }

        // we reached the end of the stream.
        // stop and close the line.
        line.stop();
        line.close();
        line = null;

        // stop and close the output stream
        try {
            out.flush();
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        // load bytes into the audio input stream for playback
        byte audioBytes[] = out.toByteArray();
        ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);

        audioInputStream = new AudioInputStream(bais, format, audioBytes.length / frameSizeInBytes);

        long milliseconds = (long) ((audioInputStream.getFrameLength() * 1000) / format.getFrameRate());

        duration = milliseconds / 1000.0;

        try {
            AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, new File(voiceOutput));

            sendSound();

        } catch (IOException ex) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

    public void sendSound() throws IOException {

        connection2 = new Socket(InetAddress.getByName(serverIP), 1990);
        System.out.println("send voice");
        OutputStream output2 = new ObjectOutputStream(connection2.getOutputStream());
        output2.flush();
        InputStream input2 = new ObjectInputStream(connection2.getInputStream());
        System.out.println(input2);

        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(connection2.getOutputStream());
        } catch (IOException ex1) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex1);
            System.out.println("error creating data input stream ");
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(voiceOutput);

        } catch (FileNotFoundException ex1) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex1);
            System.out.println("error in creating file input stream");

        }

        int count = 0;
        byte[] buffer = new byte[4096];

        try {
            while ((count = fis.read(buffer)) > 0) {
                dos.write(buffer, 0, count);
                dos.flush();
                System.out.println(fis);
            }
        } catch (IOException ex1) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex1);
            System.out.println("error in loop writing");
        }

        try {

            fis.close();
        } catch (IOException ex1) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex1);
            System.out.println("error closing fis");
        }
        try {
            dos.flush();
            dos.close();

        } catch (IOException ex1) {
            Logger.getLogger(EchoRun.class.getName()).log(Level.SEVERE, null, ex1);
            System.out.println("or closing dos");
        }

    }

}

1 个答案:

答案 0 :(得分:0)

这一行:

String serverIP = InetAddress.getLocalHost().getHostAddress();

IIRC,这会将serverIP变量设置为本地主机的IP地址,即127.0.0.1。这是一个环回地址,仅适用于同一设备。

您需要告诉客户端连接到路由器分配的服务器的IP地址(通常以192.168开头...在小型网络上)。

如果您使用的是Windows设备,则可以使用命令提示符中的ipconfig命令查找此信息,或者我认为Linux上的ifconfig

相关问题