2015-12-25 77 views
1

我正尝试使用本地网络在计算机上的java服务器设置和智能手机上的android客户端设置之间建立通信应用程序。 问题是在客户端套接字的构造函数中,我通过了服务器IP地址,虽然没有建立连接。 下面是这两个文件的详细信息:无法在java服务器和Android客户端之间建立连接

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

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 
      } 
     } 


} 

} 

至于清单文件,这些权限补充: ACCESS_NETWORK_STATE ACCESS_WIFI_STATE CHANGE_WIFI_STATE INTERNET CHANGE_NETWORK_STATE

回答

0

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

+0

对不起,我忘了共享清单文件,但所有必需的权限已添加: –

+0

是的,只是一个猜测(但通常是这样)。所以,请发布你正在收到的错误堆栈痕迹 –

+0

没有错误,客户端找不到服务器。 –

相关问题