简体   繁体   English

无法在Java服务器和Android客户端之间建立连接

[英]Unable to establish a connection between a java server and an android client

I'm trying to build a communication application between a java server setup on a computer, and an android client setup on a smartphone, using a local network. 我正在尝试使用局域网在计算机上的Java服务器设置与智能手机上的android客户端设置之间构建通信应用程序。 The problem is in the constructor of the client Socket, I passed the server IP address though no connection was established. 问题出在客户端套接字的构造函数中,尽管没有建立连接,但我还是传递了服务器IP地址。 Here are the two files for more details: 以下是这两个文件的更多详细信息:

Server.java Server.java

public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;

//constructor
public Server(){
    super("Networking Test");
    userText = new JTextField();
    userText.setEditable(false);
    userText.addActionListener(
            new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    sendMessage(event.getActionCommand());
                    userText.setText("");

                }
            }
            );
    add(userText, BorderLayout.NORTH);
    chatWindow = new JTextArea();
    add(new JScrollPane(chatWindow));
    setSize(300,150);
    setVisible(true);
}//constructor end

//setup and run the server
public void startRunning(){
    try{
        server = new ServerSocket(9999);

            try{
                waitForConnection();

                setupStreams();

                whileChatting();

            }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
            }catch(StreamCorruptedException sce){
                sce.printStackTrace();
            }

            finally{
                closeResources();
            }

    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}//startRunning() end

//wait for connection, then display connection information.
private void waitForConnection() throws IOException{
    showMessage("Waiting for the client...\n");
    connection = server.accept(); 
    showMessage(" Now connected");

}

//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 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 cnfe){
            showMessage("\n ERROR: Failed sending the message!");
        }
    }while(!message.equals("SERVER - END"));
}

//close streams and sockets
private void closeResources(){
    showMessage("\n Closing connection...\n");
    ableToType(false);
    try{
        output.close();
        input.close();
        connection.close();
    }catch(IOException ioe){
        ioe.printStackTrace();
    }
}

//send a message to the client
        private void sendMessage(String message){
            try{
                output.writeObject("SERVER - "+message);
                output.flush();
                showMessage("\nSERVER - "+message);
            }catch(IOException ioe){
                chatWindow.append("\n EROOR: Failed sending the message!  ");
            }
        }

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


                        }
                    }
                    );
        }


        //permission to type
        private void ableToType(final boolean permission){
            SwingUtilities.invokeLater(
                    new Runnable(){
                        public void run(){
                            userText.setEditable(permission);
                        }
                    }
                    );
        }
}

MainActivity.java MainActivity.java

public class MainActivity extends Activity {

private String message = "";
private Socket connection;
ObjectOutputStream output;
private Button send;
private EditText userText;

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    isNetworkAvailable();
    Toast.makeText(getApplicationContext(), ""+isNetworkAvailable(), Toast.LENGTH_LONG).show();//for verification purposes
    new Thread (new Runnable() {

        @Override
        public void run() {
            try{
                //checkForConnection();

                init();
                listen();
            }catch(Exception e){

            }
            finally{
                //closeResources();
            }

        }
    }).start();


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

//init()
private void init() throws UnknownHostException, IOException{
    userText = (EditText) findViewById(R.id.userText);
    send = (Button) findViewById(R.id.send);
    connection = new Socket("192.168.43.178", 9999);//this is where the 
//problem is located, that is the correct IP but the connection never starts
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
}

//listen()
private void listen(){



            send.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    message = userText.getText().toString();
                    userText.setText("");
                    sendMessage(message);

                }
            });

}

//sendCommands
private void sendMessage(String message){
    try{
        output.writeObject("CLIENT - "+message);
        output.flush();
    }catch(StreamCorruptedException sce){

    }catch(IOException ioe){

    }
}

//closeResources
private void closeResources(){
    try{
    output.close();
    connection.close();
    }catch(IOException ioe){

    }
}

//check for connection
private void checkForConnection() throws IOException{
    ConnectivityManager check = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] info = check.getAllNetworkInfo();
    for (int i = 0; i<info.length; i++){
           if (info[i].getState() == NetworkInfo.State.CONNECTED){
              Toast.makeText(this, "Connection to the internet is established", Toast.LENGTH_LONG).show();//other version
           }
        }


}

}

As for the manifest file, these are the permissions added: ACCESS_NETWORK_STATE ACCESS_WIFI_STATE CHANGE_WIFI_STATE INTERNET CHANGE_NETWORK_STATE 对于清单文件,这些是添加的权限:ACCESS_NETWORK_STATE ACCESS_WIFI_STATE CHANGE_WIFI_STATE INTERNET CHANGE_NETWORK_STATE

检查服务器上的防火墙,因为Java运行时会创建其他进程来运行您的应用程序,并且您可能尚未授权所有进程通过防火墙。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM