我尝试使用本地网络在计算机上的Java服务器设置和智能手机上的Android客户端设置之间构建通信应用程序。 问题是在客户端Socket的构造函数中,虽然没有建立连接但我传递了服务器IP地址。 以下是两个文件以获取更多详细信息:
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 互联网 CHANGE_NETWORK_STATE
答案 0 :(得分:0)
检查服务器上的防火墙,因为Java运行时会创建其他进程来运行您的应用程序,并且您可能没有授权所有进程允许通过防火墙。