简体   繁体   English

服务器与android之间的连接

[英]Connection between server and android

I'm trying to develop an app for instant messaging (like whatsapp). 我正在尝试开发用于即时消息的应用程序(如whatsapp)。 I'm very confused about what type of connection i should use: socket, http or other? 我对应该使用哪种类型的连接感到非常困惑:套接字,http或其他? Do i have to use non-standard java API? 我必须使用非标准的Java API吗? For server i use java and for client i use andoid (java). 对于服务器,我使用Java;对于客户端,我使用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: 这是我的客户端类(android)发送消息:

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: 这是我的Java服务器类,等待连接:

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. 先感谢您。

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. 对于Android中的即时消息,您应该使用Google Cloud Messaging。

Introduction: 介绍:

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

Getting Started: 入门:

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

I would definitely suggest using Google Cloud Messaging here. 我肯定会建议在这里使用Google Cloud Messaging 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. 这样做的好处是,一旦设备运行了您的应用程序,您就可以使其在GCM注册,并可以根据需要向他们发送消息,这样,您就不必在一定时间后关闭套接字。

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: 这种方法将需要您实现一些服务器(例如,具有PHP的Web服务器),并使用户与之通信,因此流程如下:

  1. Your server sends a broadcast message to all registered devices telling them they have to register against the GCM service. 您的服务器会向所有注册的设备发送一条广播消息,告知它们必须针对GCM服务进行注册。

  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. 设备获取消息,然后实现BroadcastReceiver以获取纬度和经度,并通过POST请求将其发送到远程服务器,例如http://www.mysuperserver.com/getmsg.php

  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 . 前往https://console.developers.google.com With your Google account, register a new project. 使用您的Google帐户注册一个新项目。 This will provide you an API key and a Sender ID. 这将为您提供API密钥和发件人ID。

  2. You'll need to make the device register against your project in GCM . 您需要在GCM针对您的项目注册设备。 You can achieve this by importing Google Play Services within your project, and once done, do something alike to this: 您可以通过在项目中导入Google Play Services来实现此目的,完成后,请执行以下操作:

     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 . 目前, GCM服务器已经知道该用户已在您的项目中注册并给了他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. 下一步是通知您自己的远程服务器用户已执行此操作,并将已提供的regid保存在某处,以便稍后向他们发送消息。 So in the client side, make a HTTP POST request against your server sending that regid and process it with somethat like this: 因此,在客户端,对发送该regid的服务器发出HTTP POST请求,并使用如下方式处理它:

     $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). 您可以SELECT所有用户,然后向他们发送新消息(模拟多播行为)。

     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. 进入客户程序后,只需处理该GCM消息并进行相应显示即可。 To process the messages I'm including a few links below. 为了处理消息,我在下面提供了一些链接。

More about this: 有关此的更多信息:

Your client is trying to connect to "ip_globale_server". 您的客户端正在尝试连接到“ ip_globale_server”。 Try using your servers ip address instead. 尝试改用服务器的IP地址。 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. 如果您的手机在3g上,则将无法连接到本地开发服务器。

Apart from that i agree with the others about gcm 除此之外,我同意其他关于gcm的观点

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

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