繁体   English   中英

服务器与android之间的连接

[英]Connection between server and android

我正在尝试开发用于即时消息的应用程序(如whatsapp)。 我对应该使用哪种类型的连接感到非常困惑:套接字,http或其他? 我必须使用非标准的Java API吗? 对于服务器,我使用Java;对于客户端,我使用Andoid(java)。 我已经尝试过套接字连接,但是没有成功。 我没有收到错误,但是什么也没发生,因为设备和服务器未连接(我不知道为什么)。

这是我的客户端类(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){}
        }
    }

}
}

这是我的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){

        }
    }

您能帮我开始吗? 先感谢您。

您应该使用推送通知。 如果您使用套接字,则连接将在某个时刻终止,并且您将无法继续接收消息。

对于Android中的即时消息,您应该使用Google Cloud Messaging。

介绍:

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

入门:

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

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

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

  1. 您的服务器会向所有注册的设备发送一条广播消息,告知它们必须针对GCM服务进行注册。

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

  3. 服务器处理参数,然后保存它们或执行所需的任何操作。

如果要遵循此方法,则必须遵循以下步骤:

  1. 前往https://console.developers.google.com 使用您的Google帐户注册一个新项目。 这将为您提供API密钥和发件人ID。

  2. 您需要在GCM针对您的项目注册设备。 您可以通过在项目中导入Google Play Services来实现此目的,完成后,请执行以下操作:

     GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); final String regid = gcm.register("YOUR_SENDER_ID"); 
  3. 目前, GCM服务器已经知道该用户已在您的项目中注册并给了他regid

  4. 下一步是通知您自己的远程服务器用户已执行此操作,并将已提供的regid保存在某处,以便稍后向他们发送消息。 因此,在客户端,对发送该regid的服务器发出HTTP POST请求,并使用如下方式处理它:

     $regid = $_POST['regid']; if (($regId) && ($ipAddr)) sql_query("INSERT INTO gcm_subscribers(regid) VALUES($regid')"); 
  5. 完成后,您将知道谁已经向您的数据库注册。 您可以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. 进入客户程序后,只需处理该GCM消息并进行相应显示即可。 为了处理消息,我在下面提供了一些链接。

有关此的更多信息:

您的客户端正在尝试连接到“ ip_globale_server”。 尝试改用服务器的IP地址。 还要确保您的电话和服务器在同一网络上。 如果您的手机在3g上,则将无法连接到本地开发服务器。

除此之外,我同意其他关于gcm的观点

暂无
暂无

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

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