summaryrefslogtreecommitdiff
path: root/android/sdremote/src/org/libreoffice/impressremote/communication/ServerFinder.java
blob: 79839e7790429e252cd17a8e074a42683893bc53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package org.libreoffice.impressremote.communication;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Collection;
import java.util.HashMap;

import org.libreoffice.impressremote.communication.Server.Protocol;

import android.content.Context;
import android.content.Intent;

public class ServerFinder {

    private Context mContext;

    private static final int PORT = 1598;
    private static final String GROUPADDRESS = "239.0.0.1";

    private static final String CHARSET = "UTF-8";

    private static final long SEARCH_INTERVAL = 1000 * 20;

    private DatagramSocket mSocket = null;

    private Thread mListenerThread = null;

    private boolean mFinishRequested = false;

    private HashMap<String, Server> mServerList = new HashMap<String, Server>();

    public ServerFinder(Context aContext) {
        mContext = aContext;
    }

    private void listenForServer() {
        byte[] aBuffer = new byte[500];
        DatagramPacket aPacket = new DatagramPacket(aBuffer, aBuffer.length);

        try {
            String aCommand = null;
            String aName = null;
            mSocket.receive(aPacket);
            int i;
            for (i = 0; i < aBuffer.length; i++) {
                if (aPacket.getData()[i] == '\n') {
                    aCommand = new String(aPacket.getData(), 0, i, CHARSET);
                    break;
                }
            }
            if (i == aBuffer.length || !aCommand.equals("LOREMOTE_ADVERTISE")) {
                return;
            }
            for (int j = i + 1; j < aBuffer.length; j++) {
                if (aPacket.getData()[j] == '\n') {
                    aName = new String(aPacket.getData(), i + 1, j - (i + 1),
                                    CHARSET);
                    break;
                }
            }
            if (aName == null) {
                return;
            }
            Server aServer = new Server(Server.Protocol.NETWORK, aPacket
                            .getAddress().getHostAddress(), aName,
                            System.currentTimeMillis());
            mServerList.put(aServer.getAddress(), aServer);
            System.out.println("Contains:<<" + aName + ">>");

            notifyActivity();
        } catch (java.net.SocketTimeoutException e) {
            // Ignore -- we want to timeout to enable checking whether we
            // should stop listening periodically
        } catch (IOException e) {
        }

    }

    public void startFinding() {
        if (mSocket != null)
            return;

        mFinishRequested = false;

        if (mListenerThread == null) {
            mListenerThread = new Thread() {
                @Override
                public void run() {
                    checkAndAddEmulator();
                    long aTime = 0;
                    try {
                        mSocket = new DatagramSocket();
                        mSocket.setSoTimeout(1000 * 10);
                        while (!mFinishRequested) {
                            if (System.currentTimeMillis() - aTime > SEARCH_INTERVAL) {
                                String aString = "LOREMOTE_SEARCH\n";
                                DatagramPacket aPacket = new DatagramPacket(
                                                aString.getBytes(CHARSET),
                                                aString.length(),
                                                InetAddress.getByName(GROUPADDRESS),
                                                PORT);
                                mSocket.send(aPacket);
                                aTime = System.currentTimeMillis();
                                // Remove stale servers
                                for (Server aServer : mServerList.values()) {
                                    if (!aServer.mNoTimeout
                                                    && System.currentTimeMillis()
                                                                    - aServer.getTimeDiscovered() > 60 * 1000) {
                                        mServerList.remove(aServer.getAddress());
                                        notifyActivity();

                                    }
                                }
                            }

                            listenForServer();
                        }
                    } catch (SocketException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            };
            mListenerThread.start();
        }

    }

    public void stopFinding() {
        if (mListenerThread != null) {
            mFinishRequested = true;
            mListenerThread = null;
        }
    }

    /**
     * Check whether we are on an emulator and add it's host to the list of
     * servers if so (although we do not know whether libo is running on
     * the host).
     */
    private void checkAndAddEmulator() {
        try {
            if (InetAddress.getByName("10.0.2.2").isReachable(100)) {
                System.out.println("NulledNot");
                Server aServer = new Server(Protocol.NETWORK, "10.0.2.2",
                                "Android Emulator Host", 0);
                aServer.mNoTimeout = true;
                mServerList.put(aServer.getAddress(), aServer);
                notifyActivity();
            }
        } catch (IOException e) {
            // Probably means we can't connect -- i.e. no emulator host
        }
    }

    /**
     * Notify the activity that the server list has changed.
     */
    private void notifyActivity() {
        Intent aIntent = new Intent(CommunicationService.MSG_SERVERLIST_CHANGED);
        mContext.sendBroadcast(aIntent);
    }

    public Collection<Server> getServerList() {
        return mServerList.values();
    }
}