2014-11-06 130 views
0

我遇到問題,我不知道是否有可能。從服務器(Java應用程序)到Android應用程序的套接字

我有一個Android應用程序是客戶端套接字。

這是爲了在Android應用程序將消息發送到服務器的代碼:

private class SendMessage extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected Void doInBackground(Void... params) { 
     try { 
      System.out.println("envia mensaje"); 
      client = new Socket("ip of server", 4444); // connect to the server 
      printwriter = new PrintWriter(client.getOutputStream(), true); 
      printwriter.write(messsage); // write the message to output stream 

      printwriter.flush(); 
      printwriter.close(); 
      client.close(); // closing the connection 

     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

} 

在同一時間,在Android應用程序,一個插座在4445端口創建:

private class SocketServerThread extends Thread { 

    static final int SocketServerPORT = 4445; 
    int count = 0; 

    @Override 
    public void run() { 
     try { 
      serverSocket = new ServerSocket(SocketServerPORT); 
      SlimpleTextClientActivity.this.runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
        System.out.println("I'm waiting here: " 
          + serverSocket.getLocalPort()); 
       } 
      }); 

      while (true) { 
       Socket socket = serverSocket.accept(); 
       count++; 
       message += "#" + count + " from " + socket.getInetAddress() 
         + ":" + socket.getPort() + "\n"; 

       SlimpleTextClientActivity.this.runOnUiThread(new Runnable() { 

        @Override 
        public void run() { 
         System.out.println(message); 
        } 
       }); 

       /*SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
         socket, count); 
       socketServerReplyThread.run();*/ 

      } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

} 

而且這是服務器代碼,它在4444端口創建一個套接字:

public static void main(String[] args) { 
    try { 
     serverSocket = new ServerSocket(4444); // Server socket 

    } catch (IOException e) { 
     System.out.println("Could not listen on port: 4444"); 
    } 

    System.out.println("Server started. Listening to the port 4444"); 


    while (true) { 
     try { 



      clientSocket = serverSocket.accept(); // accept the client connection 
      inputStreamReader = new InputStreamReader(clientSocket.getInputStream()); 
      bufferedReader = new BufferedReader(inputStreamReader); // get the client message 
      message = bufferedReader.readLine(); 



      System.out.println("Dirección entrante"+clientSocket.getInetAddress()); 
      //System.out.println("Dirección entrante2"+clientSocket.get()); 

      System.out.println(message); 


       ip_a = clientSocket.getInetAddress().toString().substring(clientSocket.getInetAddress().toString().indexOf("/")+1, clientSocket.getInetAddress().toString().length()); 
         //message.substring(message.indexOf(":")+1, message.length()).trim(); 
       System.out.println("realiza conexión a ip:#"+ip_a+"#"); 
       messsage = "enviado desde el servidor"; // get the text message on the text field 


       SendMessage(ip_a); 




      inputStreamReader.close(); 
      clientSocket.close(); 

     } catch (IOException ex) { 
      System.out.println("Problem in message reading"); 
     } 
    } 

} 

這個工作正常,但我想發送一個mes從服務器到通過套接字所具有的IP的Android設備。

我嘗試使用clientSocket.getInetAddress()和clientSocket.getRemoteSocketAddress(),但無法正常工作。我在4445端口的Android應用程序中創建了一個套接字,但服務器無法連接到Android應用程序的套接字。

你能幫我嗎?

在此先感謝

+0

你爲什麼要創建兩臺服務器?請解釋爲你的整個設置和目標對我來說不清楚。 – greenapps 2014-11-06 12:18:45

+0

我希望2個應用程序可以通過服務器java應用程序進行通信。 – tiomelenas 2014-11-06 14:45:22

+0

好的。但請花時間來解釋整個場景。我需要從代碼中發現嗎? – greenapps 2014-11-06 14:50:17

回答

0

好的,我會盡力的。

這是我的服務器aplication:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.NetworkInterface; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.net.SocketException; 
import java.net.UnknownHostException; 
import java.util.Enumeration; 


public class SimpleTextServer { 

private static ServerSocket serverSocket; 
private static Socket clientSocket; 
private static InputStreamReader inputStreamReader; 
private static BufferedReader bufferedReader; 
private static String message; 
private static Socket client; 
private static String messsage; 
private static PrintWriter printwriter; 
static String ip_a; 

public static void main(String[] args) { 
    try { 
     serverSocket = new ServerSocket(4444); // Server socket 

    } catch (IOException e) { 
     System.out.println("Could not listen on port: 4444"); 
    } 

    System.out.println("Server started. Listening to the port 4444"); 
    System.out.println("Server started. Listening to the port 4444:"+getIpAddress()); 

    while (true) { 
     try { 



      clientSocket = serverSocket.accept(); // accept the client connection 
      inputStreamReader = new InputStreamReader(clientSocket.getInputStream()); 
      bufferedReader = new BufferedReader(inputStreamReader); // get the client message 
      message = bufferedReader.readLine(); 



      System.out.println("Dirección entrante"+clientSocket.getInetAddress()); 
      //System.out.println("Dirección entrante2"+clientSocket.get()); 

      System.out.println(message); 


       ip_a = clientSocket.getInetAddress().toString().substring(clientSocket.getInetAddress().toString().indexOf("/")+1, clientSocket.getInetAddress().toString().length()); 
         //message.substring(message.indexOf(":")+1, message.length()).trim(); 
       System.out.println("realiza conexión a ip:#"+ip_a+"#"); 
       messsage = "enviado desde el servidor"; // get the text message on the text field 


       SendMessage(ip_a); 




      inputStreamReader.close(); 
      clientSocket.close(); 

     } catch (IOException ex) { 
      System.out.println("Problem in message reading"); 
     } 
    } 

} 






public static void SendMessage(String ip) { 


     try { 
      System.out.println("comienza a enviar mensaje"); 
      client = new Socket(ip, 4445); // connect to the server 
      printwriter = new PrintWriter(client.getOutputStream(), true); 
      printwriter.write(messsage); // write the message to output stream 

      printwriter.flush(); 
      printwriter.close(); 
      client.close(); // closing the connection 

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

    } 

} 

public static String getIpAddress() { 
    String ip = ""; 
    try { 
     Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface 
       .getNetworkInterfaces(); 
     while (enumNetworkInterfaces.hasMoreElements()) { 
      NetworkInterface networkInterface = enumNetworkInterfaces 
        .nextElement(); 
      Enumeration<InetAddress> enumInetAddress = networkInterface 
        .getInetAddresses(); 
      while (enumInetAddress.hasMoreElements()) { 
       InetAddress inetAddress = enumInetAddress.nextElement(); 

       if (inetAddress.isSiteLocalAddress()) { 
        ip += "SiteLocalAddress: " 
          + inetAddress.getHostAddress() + "\n"; 
       } 

      } 

     } 

    } catch (SocketException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     ip += "Something Wrong! " + e.toString() + "\n"; 
    } 

    return ip; 
} 

}

這是我在我的Android應用程序的活動:

package com.lakj.comspace.simpletextclient; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.NetworkInterface; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.net.SocketException; 
import java.net.UnknownHostException; 
import java.util.Enumeration; 

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 


public class SlimpleTextClientActivity extends Activity { 

private Socket client; 
private PrintWriter printwriter; 
private EditText textField; 
private Button button; 
private String messsage; 
//ServerSocket serverSocket; 

private static ServerSocket serverSocket; 
private static Socket clientSocket; 

private static InputStreamReader inputStreamReader; 
private static BufferedReader bufferedReader; 
private static String message; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_slimple_text_client); 

    textField = (EditText) findViewById(R.id.editText1); // reference to the text field 
    button = (Button) findViewById(R.id.button1); // reference to the send button 



    System.out.println("IP DE CLIENTE EMULADOR: "+getIpAddress()); 
    Thread socketServerThread = new Thread(new SocketServerThread()); 
    socketServerThread.start(); 


    //myClientTask.execute(); 

    // Button press event listener 
    button.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      System.out.println("ENVIA MENSAJE BOTON"); 
      messsage = textField.getText().toString(); // get the text message on the text field 
      textField.setText(""); // Reset the text field to blank 
      SendMessage sendMessageTask = new SendMessage(); 
      sendMessageTask.execute(); 
     } 
    }); 
} 

private class SendMessage extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected Void doInBackground(Void... params) { 
     try { 
      System.out.println("envia mensaje"); 
      client = new Socket("ip de servidor", 4444); // connect to the server 
      printwriter = new PrintWriter(client.getOutputStream(), true); 
      printwriter.write(messsage); // write the message to output stream 

      printwriter.flush(); 
      printwriter.close(); 
      client.close(); // closing the connection 

     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

} 

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

private class SocketServerThread extends Thread { 

    static final int SocketServerPORT = 4445; 
    int count = 0; 

    @Override 
    public void run() { 
     try { 
      serverSocket = new ServerSocket(SocketServerPORT); 
      SlimpleTextClientActivity.this.runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
        System.out.println("I'm waiting here: " 
          + serverSocket.getLocalPort()); 
       } 
      }); 

      while (true) { 
       Socket socket = serverSocket.accept(); 
       count++; 
       message += "#" + count + " from " + socket.getInetAddress() 
         + ":" + socket.getPort() + "\n"; 

       SlimpleTextClientActivity.this.runOnUiThread(new Runnable() { 

        @Override 
        public void run() { 
         System.out.println(message); 
        } 
       }); 

       /*SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
         socket, count); 
       socketServerReplyThread.run();*/ 

      } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

} 



@Override 
protected void onDestroy() { 
    super.onDestroy(); 

    if (serverSocket != null) { 
     try { 
      serverSocket.close(); 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 

private String getIpAddress() { 
    String ip = ""; 
    try { 
     Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface 
       .getNetworkInterfaces(); 
     while (enumNetworkInterfaces.hasMoreElements()) { 
      NetworkInterface networkInterface = enumNetworkInterfaces 
        .nextElement(); 
      Enumeration<InetAddress> enumInetAddress = networkInterface 
        .getInetAddresses(); 
      while (enumInetAddress.hasMoreElements()) { 
       InetAddress inetAddress = enumInetAddress.nextElement(); 

       if (inetAddress.isSiteLocalAddress()) { 
        ip += "SiteLocalAddress: " 
          + inetAddress.getHostAddress() + "\n"; 
       } 

      } 

     } 

    } catch (SocketException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     ip += "Something Wrong! " + e.toString() + "\n"; 
    } 

    return ip; 
} 

}

如果我運行Android應用,該消息被髮送到服務器,並且服務器顯示它。

但是,服務器無法連接到Android。 IP是不可接受的。我不知道爲什麼......

相關問題