문제

I'm trying to develop an app for instant messaging (like whatsapp). I'm very confused about what type of connection i should use: socket, http or other? Do i have to use non-standard java API? For server i use java and for client i use andoid (java). I have already tried socket connection but without success. I don't get error but nothing happens because the device and the server are not connected(i don't know why).

This is my client class (android) that sends messages:

public class SendMsg implements Runnable {

private Socket socket;
String msg;

public SendMsg(String msg){
    this.msg=msg;
    }

@Override
public void run() {


    try {
        socket = new Socket("ip_globale_server",5000);
        socket.setSoTimeout(5000);
        BufferedWriter writer= new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write(msg);
        writer.flush();
    }
    catch (IOException e){
        System.err.println("Connection error");
    }
    finally{
        if (socket!=null) {
        try{socket.close();}
        catch(IOException e){}
        }
    }

}
}

this is my java server class that waits for connection:

public class ReceiveMsg implements Runnable {

ServerSocket server= null;
Socket connection=null;
InputStream in;
InputStreamReader inr;
StringBuilder smsg;


public void run() {
    System.out.print("Server has started");

    try {
        server = new ServerSocket(5000);
        System.out.println("I'm waiting for connection");
        connection = server.accept();
        System.out.println("I'm connected with "+ connection.toString());
        in = connection.getInputStream();
        inr = new InputStreamReader(in,"ASCII");
        for (int c= inr.read();c!=-1; c= inr.read()){
            smsg.append((char)c);
        }

        //this class is for storing the message
        new Store (smsg.toString(),1,2);

    }
    catch(IOException ex){}
    finally {
        try{
        if (server != null)
            server.close();

        if (server != null)
            server.close();

        }
        catch(IOException e){

        }
    }

Could you help me to get start please. Thank you in advance.

도움이 되었습니까?

해결책

I would definitely suggest using Google Cloud Messaging here. This has the benefit that once a device runs your app, you can make it register against GCM and you can send them the messages as needed, this way you don't have to struggle with sockets that close after a certain amount of time.

This approach would need that you have to implement some server (for instance, a web server with PHP) and make the users communicate with it, so the flow would be:

  1. Your server sends a broadcast message to all registered devices telling them they have to register against the GCM service.

  2. The devices get the message, and you implement the BroadcastReceiver to get both latitude and longitude and send it to your remote server, say http://www.mysuperserver.com/getmsg.php, via a POST request.

  3. Your server processes the parameters and you save them or do whatever you need.

If you want to follow this approach, this are the steps you have to follow:

  1. Go to https://console.developers.google.com. With your Google account, register a new project. This will provide you an API key and a Sender ID.

  2. You'll need to make the device register against your project in GCM. You can achieve this by importing Google Play Services within your project, and once done, do something alike to this:

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
    final String regid = gcm.register("YOUR_SENDER_ID");
    
  3. At this time, the GCM server already knows that this user has registered whithin your project and has given him a regid.

  4. The next step is informing your own remote server that the user has done so, and save somewhere the regid that it has been given, so you can later send them messages. So in the client side, make a HTTP POST request against your server sending that regid and process it with somethat like this:

    $regid = $_POST['regid'];
    
    if (($regId) && ($ipAddr))
      sql_query("INSERT INTO gcm_subscribers(regid) VALUES($regid')");
    
  5. Once done, you know who have already registered against your database. You can SELECT all the users and send them the new messages (simulating a multicast behavior).

    function sendNotification($registrationIdsArray, $messageData) {
      $apiKey = "YOUR_API_KEY";
    
      $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
      $data = array(
        'data' => $messageData,
        'registration_ids' => $registrationIdsArray
      );
    
      $ch = curl_init();
    
      curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
      curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
      curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
      curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
      curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
      curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
    
      $response = curl_exec($ch);
      curl_close($ch);
    
      return $response;
    }
    
  6. Once in your client, just process that GCM message and display it accordingly. To process the messages I'm including a few links below.

More about this:

다른 팁

You should use Push Notifications. If you use sockets, the connection will terminate at some point and you'll not be able to keep receiving messages.

For instant messages in android you should use Google Cloud Messaging.

Introduction:

  http://developer.android.com/google/gcm/index.html

Getting Started:

  http://developer.android.com/google/gcm/gs.html

Your client is trying to connect to "ip_globale_server". Try using your servers ip address instead. Also make sure your phone and server are on the same network. If your phone is on 3g it will not be able to connect to your local development server.

Apart from that i agree with the others about gcm

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top