2016-04-20 13 views
0

サーバークラスを設定しようとしていますが、エラーがスローされていない問題が発生しています。Javaサーバークラスとソケット接続の問題

import java.io.*; 
import java.net.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class Server extends JFrame implements Runnable{ 

private static final long serialVersionUID = 1L; 
private JTextField userText; 
private JTextArea chatWindow; 
private ObjectOutputStream output; 
private ObjectInputStream input; 
private ServerSocket server; 
private Socket connection; 

//constructor 
public Server(){ 
    super("Server"); 
    userText = new JTextField(); 
    userText.setEditable(false); 
    userText.addActionListener(
     new ActionListener(){ 
      public void actionPerformed(ActionEvent event){ 
       sendMessage(event.getActionCommand()); 
       userText.setText(""); 
      } 
     } 
    ); 
    add(userText, BorderLayout.NORTH); 
    chatWindow = new JTextArea(); 
    add(new JScrollPane(chatWindow)); 
    setSize(300, 150); //Sets the window size 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setVisible(true); 
} 

public void run(){ 
    try{ 
     server = new ServerSocket(6789, 100); //6789 is a dummy port for testing, this can be changed. The 100 is the maximum people waiting to connect. 
     while(true){ 
      try{ 
       //Trying to connect and have conversation 
       waitForConnection(); 
       setupStreams(); 
       whileChatting(); 
      }catch(EOFException eofException){ 
       showMessage("\n Server ended the connection! "); 
      } finally{ 
       closeConnection(); //Changed the name to something more appropriate 
      } 
     } 
    } catch (IOException ioException){ 
     ioException.printStackTrace(); 
    } 
} 
//wait for connection, then display connection information 
private void waitForConnection() throws IOException{ 
    showMessage(" Waiting for someone to connect... \n"); 
    connection = server.accept(); 
    showMessage(" Now connected to " + connection.getInetAddress().getHostName()); 
} 

//get stream to send and receive data 
private void setupStreams() throws IOException{ 
    output = new ObjectOutputStream(connection.getOutputStream()); 
    output.flush(); 

    input = new ObjectInputStream(connection.getInputStream()); 

    showMessage("\n Streams are now setup \n"); 
} 

//during the chat conversation 
private void whileChatting() throws IOException{ 
    String message = " You are now connected! "; 
    sendMessage(message); 
    ableToType(true); 
    do{ 
     try{ 
      message = (String) input.readObject(); 
      showMessage("\n" + message); 
     }catch(ClassNotFoundException classNotFoundException){ 
      showMessage("The user has sent an unknown object!"); 
     } 
    }while(!message.equals("CLIENT - END")); 
} 

public void closeConnection(){ 
    showMessage("\n Closing Connections... \n"); 
    ableToType(false); 
    try{ 
     output.close(); //Closes the output path to the client 
     input.close(); //Closes the input path to the server, from the client. 
     connection.close(); //Closes the connection between you can the client 
    }catch(IOException ioException){ 
     ioException.printStackTrace(); 
    } 
} 

//Send a mesage to the client 
private void sendMessage(String message){ 
    try{ 
     output.writeObject("SERVER - " + message); 
     output.flush(); 
     showMessage("\nSERVER -" + message); 
    }catch(IOException ioException){ 
     chatWindow.append("\n ERROR: CANNOT SEND MESSAGE, PLEASE RETRY"); 
    } 
} 

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

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



import java.awt.Dimension; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 


import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 

public class Menu extends JFrame implements ActionListener{ 

private static final long serialVersionUID = 1L; 
private JButton server; 
private JButton client; 
private static String Host; 

public Menu(){ 

    this.getContentPane().setPreferredSize(new Dimension(300, 300)); 

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setLayout(null); 
    this.pack(); 

    this.setLocationRelativeTo(null); 

    server = new JButton(); 
    server.setText("server"); 
    server.setBounds(0, 0, 300, 150); 
    server.addActionListener(this); 
    client = new JButton(); 
    client.setText("client"); 
    client.setBounds(0, 150, 300, 150); 
    client.addActionListener(this); 

    this.add(server); 
    this.add(client); 

    this.setVisible(true); 
} 


public void actionPerformed(ActionEvent e) { 
    if(e.getSource() == server){ 
     Server s = new Server(); 
     s.run(); 
    } 
    if(e.getSource() == client){ 
     Host = JOptionPane.showInputDialog("Enter Server I.P."); 
     Client c = new Client(Host); 
     c.run(); 
    } 

} 

public static void main(String[] args){ 
    new Menu(); 
} 

} 

のJFrameが作成され、だけではないdefault_exit_on_close動作、Eclipseの終了ボタンで終了することができ、そして(それがあるべきように不透明ではない)を介して参照されます。クライアントクラスは、問題があると信じて私をリードし、同じように動作します

Server s = new Server(); 
     s.run(); 

私は、すべてが正常に動作することを主なメソッド呼び出しを持っている場合以来。

答えて

0

あなたのコンストラクタは決して終了できません。

このwaitForConnection()/setUpStreams()ロジックは適切ではありません。受け入れるループが必要です。ソケットを受け取り、接続を処理するためにRunnableを構成し、スレッドを開始します。そのループは別のrun()メソッドにあり、別のスレッドで実行する必要があります。コンストラクタではありません。

NB accept()によって返されるSocketは、そうしないと、並行性の問題に実行しやすい、そのループ内のローカル変数でなければなりません。

+0

チュートリアルから正確なコードをコピーしたとき(私はそれをRunnableにしたので)、うまくいきました。彼は主な方法を作成して、サーバーを作成するしかありませんでした。しかし、メニュークラスを作成してjbuttonを使ってサーバーを構築すると、同じ問題が発生し、サーバーの構築方法に問題があると私は思っています。私もチュートリアルのコードと私のメニュークラスを追加しました – Deek3117

+0

元の問題を解決したかどうかは、すべて理解できません。 AWTイベント・スレッドではなく、サーバーとクライアントの両方を別々のスレッドで実行する必要があります。このコードがチュートリアルのものであれば、より良いコードを見つけるべきです。サーバーがJavaで書かれている方法ではありません。 – EJP

+0

AWTイベント・スレッド(JButtons)でサーバーを実行することは、非常に懇願して以来、問題であり、私はそれが事実であることに気付かず、当初はどこか他の場所にいると想定していました。私はうまくいけば、私のメニュークラスで達成することを望んでいたサーバまたはクライアントとして使えるゲームを作っています。 – Deek3117