1

Javaソケットネットワークを使用したBuckyのインスタントメッセンジャーチュートリアルについて聞いたことがあるかもしれません。127.0.0.1簡単にまとめると、彼はIPアドレスを使用してクライアントとサーバー間の接続を作成しているということです。すべてがうまくいきましたが、コードを変更して2台の別々のコンピューター(クライアントとサーバー)に配置しようとすると、接続が確立されません。私は何が間違っているのですか?

サーバーコード

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

public class Server extends JFrame{

private JTextField userTextField;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;

//constructor
public Server()
{

    super("My Instant Messenger");
    userTextField = new JTextField();
    userTextField.setEditable(false);

    userTextField.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent event)
     {

        sendMessage(event.getActionCommand());
        userTextField.setText("");

     }
    }
    );

    add(userTextField, BorderLayout.NORTH);
    chatWindow = new JTextArea();
    add(new JScrollPane(chatWindow));
    setSize(300,150);
    setVisible(true);
}


//set up and run the server

public void startRunning(){
 try{

  server = new ServerSocket(6789,100);
  while(true)
  {
      try{

          waitForConnection();
          setupStreams();
          whileChatting();

      }catch(EOFException e){
       showMessage("\n Server ended the connection! ");  
      }finally{
       closeCrap();  
      }
  }

 }catch(IOException e){
  e.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 coversation
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 e){
            showMessage("\n idk wtf that user sent!");
        }
    }while(!message.equals("CLIENT - END"));
}

//close streams and sockets after you are done chating
private void closeCrap(){
    showMessage("\n Closing connection... \n");
    ableToType(false);
    try{

        output.close();
        input.close();
        connection.close();

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

//send a message to client
private void sendMessage (String message){
    try{

        output.writeObject("SERVER -  " + message);
        output.flush();
        showMessage("\nSERVER - " + message);

    }catch(IOException e){
        chatWindow.append("\n ERROR: DUDE I CANT SEND THAT MESSAGE!");
    }
}    

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

//let the user type stuff into their box
private void ableToType(final boolean tof){
    SwingUtilities.invokeLater(
    new Runnable(){
    public void run(){
        userTextField.setEditable(tof);
    }
    }
    );
}

public static void main(String[] args){
    Server sally = new Server();
    sally.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    sally.startRunning();
}

}

クライアントコード

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

public class Client extends JFrame{
private JTextField userTextField;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;

//constructor
public Client(String host){

    super("Client");
    serverIP = host;
    userTextField = new JTextField();
    userTextField.setEditable(false);
    userTextField.addActionListener(
        new ActionListener(){
            public void actionPerformed(ActionEvent event){
                sendMessage(event.getActionCommand());
                userTextField.setText("");
            }
        }
    );
    add(userTextField, BorderLayout.NORTH);
    chatWindow = new JTextArea();
    add(new JScrollPane(chatWindow), BorderLayout.CENTER);
    setSize(300,150);
    setVisible(true);
}

//connect to server
public void startRunning(){
    try{
        connectToServer();
        setUpStreams();
        whileChatting();
    }catch(EOFException e){
        showMessage("\n Client terminated connection");
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        closeCrap();
    }
}

//connect to server
private void connectToServer() throws IOException{
    showMessage("Attempting connection... \n");
    connection = new Socket(InetAddress.getByName(serverIP), 6789);
    showMessage("Connected to: " + connection.getInetAddress().getHostName());
}

//set up streams to send and receive messages
private void setUpStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("\n Dude your streams are now good to go! \n");
}

//while chating with server
private void whileChatting() throws IOException{
    ableToType(true);
    do{
        try{
            message = (String) input.readObject();
            showMessage("\n" + message);
        }catch(ClassNotFoundException e){
            showMessage("\n i dont know that object type");
        }
    }while(!message.equals("SERVER - END"));
}

//close the streams and sockets
private void closeCrap(){
    showMessage("\n closing crap down...");
    ableToType(false);
    try{
        output.close();
        input.close();
        connection.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

//send messages to server
private void sendMessage(String message){
    try{
        output.writeObject("CLIENT - " + message);
        output.flush();
        showMessage("\nCLIENT - " + message);
    }catch(IOException e){
        chatWindow.append("\n something messed up sending message host!");
    }
}

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

//gives user permission to type crap into the text box
private void ableToType(final boolean tof){
    SwingUtilities.invokeLater(
        new Runnable(){
            public void run(){
                userTextField.setEditable(tof);
            }
        }
    );
}

public static void main (String[] args){
    Client charlie;
    charlie = new Client("127.0.0.1");
    charlie.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    charlie.startRunning();
}
}
4

1 に答える 1

0

問題は、IPv4およびv6を使用するプラットフォームで実行する場合のJava自体です。

serverSocketをIPv4アドレスにバインドしてみてください。"0.0.0.0"これは、このホストで使用可能なすべてのIPを意味するか、クライアントコードにあるIPを使用します(192.168.x.x

このような

server = new ServerSocket(6789, 100, InetAddress.getByName("0.0.0.0"));
于 2013-03-23T23:36:11.827 に答える