【问题标题】:How to create server to use chat room realtime (SignalR) in android如何在android中创建服务器以使用聊天室实时(SignalR)
【发布时间】:2015-02-28 16:48:53
【问题描述】:

我是 android xamarin 的初学者。我想使用 SignalR 实时使用聊天室。但我不知道这个例子中的“http://10.0.2.2:8081/echo”是什么意思。它是服务器吗???该服务器中有一些东西 - 比如 php 文件、数据库或其他东西??? 希望您的回答,谢谢:D 或任何人告诉我如何构建群聊应用程序,请(使用套接字,如:http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-1/ 或 xamarin 中的 SignalR)

using System.Collections.Generic;  
using Android.App;  
using Android.OS;  
using Android.Widget;

namespace SignalR.Client.MonoDroid.Sample  
{
[Activity(Label = "SignalR.Client.MonoDroid.Sample", MainLauncher = true, Icon = "@drawable/icon")]
public class DemoActivity : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.Main);

        var messageListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, new List<string>());
        var messageList = FindViewById<ListView>(Resource.Id.Messages);
        messageList.Adapter = messageListAdapter;

        var connection = new Connection("http://10.0.2.2:8081/echo");
        connection.Received += data => 
            RunOnUiThread(() => messageListAdapter.Add(data));

        var sendMessage = FindViewById<Button>(Resource.Id.SendMessage);
        var message = FindViewById<TextView>(Resource.Id.Message);

        sendMessage.Click += delegate
        {
            if (!string.IsNullOrWhiteSpace(message.Text) && connection.State == ConnectionState.Connected)
            {
                connection.Send("Android: " + message.Text);

                RunOnUiThread(() => message.Text = "");
            }
        };

        connection.Start().ContinueWith(task => connection.Send("Android: connected"));
    }
}

}

【问题讨论】:

    标签: android xamarin signalr chat


    【解决方案1】:

    10.0.x.x 是一个私有子网 (http://en.wikipedia.org/wiki/Private_network)。在此示例中,它是在谈论您在计算机上的 8081 端口上运行某种服务器系统。

    【讨论】:

      【解决方案2】:
      http://10.0.2.2:8081/echo
      
      
      10.0.2.2 is the ip of your server
      8081 is the port on which server listening your request and give response on same port
      
      echo is the automated generate respone which is given to you on every request with same request(String)
      
          public static class  MyClientTask extends AsyncTask<Void, Void, Void> {
                String dstAddress;
                int dstPort;
                String response = "";
                String s;
                String red;
                String loc;
                public MyClientTask(String addr, int port,String msg){
                 dstAddress = addr;
                 dstPort = port;
                 loc=msg;
                }
                @Override
                protected Void doInBackground(Void... arg0) {
                 Socket socket = null;
                 DataOutputStream   dataOutputStream = null;
                 ObjectInputStream inputStream=null;
      
                 try {
                     SocketAddress socketAddress = new InetSocketAddress(dstAddress,dstPort);
                     socket = new Socket();
                     socket.setTcpNoDelay(true);
                     socket.setSoTimeout(5000);
                     socket.connect(socketAddress, 50000);
                //  socket = new Socket(dstAddress, dstPort);
                    System.setProperty("http.keepAlive", "false");
               dataOutputStream = new DataOutputStream(socket.getOutputStream());
               dataOutputStream.writeUTF(loc);
               ///inputStream = new ObjectInputStream(socket.getInputStream());
               InputStream is = socket.getInputStream();
               PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
               BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
               out.println(""); 
               //response = br.readLine();
               try{
                      while((s=br.readLine())!=null){
                          red=red+s;
                    Log.i("server", ""+red);
                      }
                      Log.i("server", ""+red);
                  }catch(Exception ex){
                          ex.printStackTrace();
                  }
                  Log.i("Server response ", "hi"+s);
                 try {
      
                     System.out.println("Read back from server: " + response);
                  }
                  catch(Exception e) {
                       Log.i("Server response ", response+e);
                  }
      
      
                 } catch (UnknownHostException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  response = "UnknownHostException: " + e.toString();
                 } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  response = "IOException: " + e.toString();
                 }finally{
                  if(socket != null){
                   try {
                       dataOutputStream.flush();
                        socket.close();
                   } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                   }
                  }
                 }
                 return null;
                }
                @Override
                protected void onPostExecute(Void result) {
                       res=response;
                    Log.i("response:", "res"+res);
                  //  Toast.makeText(getApplicationContext(), "hi"+res, Toast.LENGTH_LONG).show();
                 super.onPostExecute(result);
                }
      
               }
      
      
      
      call this method to send request and get response on your desired place
      
      public void sendtoserver(String msg){
              if(isConnectingToInternet()){
      
                  servermsg="$loc"+","+ieminumber+","+formattedDate2+","+formattedDate1+","+formattedDate2+","+formattedDate1+","+1+","+lat1+","+"N"+","+lon1+"*";
      //10.0.2.2:8081/echo
                      MyClientTask myClientTask = new MyClientTask(
                                 "10.0.2.2",8081,msg);
                               myClientTask.execute();
                  }
      
              }
      

      【讨论】:

        【解决方案3】:

        如果您在模拟器上运行您的应用,并且您的服务器与模拟器在同一台电脑上运行,那么您的客户端应用可以访问该服务器的唯一方法是使用 ip 10.0.2.2,因为 Google 以这种方式实现了它。同时,您的计算机可以拥有像 192.168.1.12 这样的本地 ip,但您的应用程序不能使用它。此外,运行在同一台 PC 上的客户端可以通过 localhost 或 127.0.0.1 访问 PC 上的服务器。您的应用程序不在该电脑上运行。您的应用在模拟器上运行。

        【讨论】:

          猜你喜欢
          • 2011-11-06
          • 1970-01-01
          • 1970-01-01
          • 2012-06-25
          • 1970-01-01
          • 2012-12-17
          • 1970-01-01
          • 1970-01-01
          • 2021-11-04
          相关资源
          最近更新 更多