如何创建服务器以在android中实时使用聊天室(SignalR)

时间:2015-02-28 06:01:53

标签: android xamarin signalr chat

我是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/或SignalR in xamarin)

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"));
    }
}

}

3 个答案:

答案 0 :(得分:0)

10.0.x.x是一个私有子网(http://en.wikipedia.org/wiki/Private_network)。在这个例子中,它说的是你在端口8081上运行某种服务器系统。

答案 1 :(得分:0)

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();
            }

        }

答案 2 :(得分:0)

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