2016-04-16 21 views
-1

私のサーバーアプリケーションとクライアントアプリケーションを接続しようとしていますが、自分のコンピューター(ホスト)細かいメッセージを送信するなど私はゲストのコンピュータのためのJARファイルを起動するときにそれはストリームを閉じます...私はwifiの設定などのコンテキストでここで行方不明な何かが重要ですか?これは私の最初のソケットアプリケーションなので、私は明らかにこの材料の専門家ではありませんが、あなたが親切に私を正しい方向に向けることができれば、大きな感謝の問題を指摘することができます。クライアントとサーバーがローカルネットワーク経由で接続されていません

HOST:

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

    } 

} 

答えて

0

このライン:

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

IIRC、これは127.0.0.1で、ローカルホストのIPアドレスにserverIP変数を設定します。これはループバックアドレスであり、同じデバイス上でのみ動作します。

ルータに割り当てられたサーバのIPアドレスに接続するようにクライアントに伝える必要があります(通常、小規模ネットワークでは192.168 ...と始まります)。

Windowsデバイスを使用している場合は、コマンドプロンプトでipconfigコマンドを使用してこの情報を検索するか、またはLinuxのifconfigと考えることができます。

+0

返信ありがとうルーク私は自分のIPを取得しました。要するに、HOSTアプリケーションの標準127.0.0.1ホストにserverIPを変更し、クライアント側でIPアドレスを取得する方法を作成しますか?この結果を得ることができることを知っているドキュメントやサンプルコードはありますか?ありがとうございます – Sleeking

+0

あなたのサーバー上の何かを変更する必要はありません。クライアントにどこに接続するかを伝える必要があります。サーバIPが何であるかを「発見」する方法はありません。クライアントはそれを知りません。この値は通常、ハードコーディングされているか、ファイルから読み込まれます。 –

+0

申し訳ありませんが、ServerIPがあるクライアント側のホストのIPアドレスを入力してください。 – Sleeking

関連する問題