Back to project page AndroidWifiServer.
The source code is released under:
Apache License
If you think the Android project AndroidWifiServer listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package jp.maju.wifiserver.server; //www.jav a 2 s. c om import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.ref.WeakReference; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Date; import java.util.List; import jp.maju.wifidetecter.reciever.ConnectionObserver; import jp.maju.wifidetecter.reciever.ConnectionObserver.OnStateListener; import jp.maju.wifiserver.CustomWebView; import jp.maju.wifiserver.DBAdapter; import jp.maju.wifiserver.HTMLBuilder; import jp.maju.wifiserver.twitter.TweetTask; import jp.maju.wifiserver.twitter.TweetTask.OnTweetResultListener; import jp.maju.wifiserver.twitter.TwitterUtils; import jp.maju.wifiserver.util.CommonUtil; import jp.maju.wifiserver.util.Logger; import jp.maju.wifiserver.util.PreferenceUtil; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.Twitter; import android.app.Notification; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.NetworkInfo; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.text.TextUtils; import android.widget.Toast; /* * Copyright {2014} {Matsuda Jumpei} * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ public class ServerService extends Service implements OnStateListener { // ,OnReceiveListener { private static final String TAG = ServerService.class.getSimpleName(); private static final int NOTIFICATION_ID = 0x23; private static final int WHAT_SHOWING_TOAST = 100; // private String beforeDeviceName; private MessageHandler mMessageHandler; private ConnectionObserver mServerObserver; // private BTBroadCastReciever mBluetoothReciever; // private BluetoothAdapter mBluetoothAdapter; // private boolean isWhileDiscoverying = true; private Thread mThread; private volatile ServerSocket mServerSocket; private int servertPort; private int connectedCount = 0; private List<Thread> accedptedRunningThreadList; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); startForeground(NOTIFICATION_ID, new Notification()); accedptedRunningThreadList = new ArrayList<Thread>(); // mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // beforeDeviceName = mBluetoothAdapter.getName(); mMessageHandler = new MessageHandler(this); mServerObserver = new ConnectionObserver(); mServerObserver.setOnStateListener(this); // mBluetoothReciever = new BTBroadCastReciever(this); // registerReceiver(mBluetoothReciever, // BluetoothUtils.getBluetoothIntentFilter()); registerReceiver(mServerObserver, CommonUtil.getNewIntentFilterWillBeRecieved()); // startDiscover(); } @Override public void onDestroy() { // endDiscover(); // if (mBluetoothReciever != null) { // unregisterReceiver(mBluetoothReciever); // } if (mServerObserver != null) { unregisterReceiver(mServerObserver); } finishServer(); // mBluetoothAdapter.setName(beforeDeviceName); super.onDestroy(); } private void showToast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } private class OpenSocketWorker implements Runnable { private boolean initSocket() { try { mServerSocket = new ServerSocket(servertPort); mServerSocket.setSoTimeout(0); Message msg = new Message(); msg.what = WHAT_SHOWING_TOAST; String m = "Open socket/" + CommonUtil.getCurrentWifiIP(getApplication()) + ":" + servertPort; msg.obj = m; mMessageHandler.sendMessage(msg); return true; } catch (IOException e) { Logger.e(TAG, e); } return false; } @Override public synchronized void run() { if (!initSocket()) { return; } try { while (true) { Socket acceptedSocket = mServerSocket.accept(); onAccepted(acceptedSocket); if (mServerSocket.isClosed()) { if (!initSocket()) { return; } } } } catch (IOException e) { Logger.e(TAG, e); } } private void onAccepted(Socket acceptedSocket) { if (acceptedSocket == null) { return; } connectedCount++; String m = "Accepted #" + connectedCount + ". From " + acceptedSocket.getInetAddress() + ":" + acceptedSocket.getPort(); Message msg = new Message(); msg.what = WHAT_SHOWING_TOAST; msg.obj = m; mMessageHandler.sendMessage(msg); accedptedRunningThreadList.add(new Thread(new ListenWorker(acceptedSocket))); accedptedRunningThreadList.get(accedptedRunningThreadList.size()-1).start(); } } private class ListenWorker implements Runnable, OnTweetResultListener { private Socket hostSocket; private BufferedReader iReader; private PrintWriter oPWriter; public ListenWorker(Socket socket) { hostSocket = socket; try { iReader = new BufferedReader(new InputStreamReader( hostSocket.getInputStream())); oPWriter = new PrintWriter(hostSocket.getOutputStream(), true); } catch (IOException e) { Logger.e(TAG, e); } } @Override public void run() { try { while (hostSocket != null && !hostSocket.isClosed() && iReader != null && !Thread.currentThread().isInterrupted()) { String read = iReader.readLine(); if (!TextUtils.isEmpty(read)) { Logger.d(TAG, read); if (read.startsWith(CustomWebView.URL_GO_REGISTER)) { sendHtmlFromAssets("register.html"); } else if (read .startsWith(CustomWebView.URL_RESULT_REGISTER)) { String params[] = CustomWebView .splitUserInfoParams(read); PreferenceUtil.registerUser(getApplication(), params[2], params[0], params[1]); sendCustomHtml(true); } else if (read .startsWith(CustomWebView.URL_RESULT_LOGIN)) { String params[] = CustomWebView .splitUserInfoParams(read); if (PreferenceUtil.verify(getApplication(), params[0], params[1])) { PreferenceUtil.addUser(getApplication(), params[2], params[0]); sendCustomHtml(true); } else { sendHtmlFromAssets("index.html"); } } else if (read.startsWith(CustomWebView.URL_GO_LOGIN)) { sendHtmlFromAssets("login.html"); } else if (read.startsWith(CustomWebView.TWEET_PREFIX)) { String unameid = read .substring(CustomWebView.TWEET_PREFIX .length()); String[] params = unameid.split(":"); long statusId = Long.parseLong(params[0]); String username = params[1]; String uuid = params[2]; boolean isLogin = (params[3].equals("true")); Twitter twitter = TwitterUtils .getRegisteredTwitterInstance( getApplication(), true); long curTime = System.currentTimeMillis(); String data = CommonUtil.formatDate(curTime); DBAdapter dbAdapter = new DBAdapter(getApplicationContext()).open(); if (isLogin) { PreferenceUtil.isDifferentDate(getApplication(), uuid + "loginlogin"); dbAdapter.login(uuid, curTime); PreferenceUtil.getPreference(getApplication()).edit().putBoolean("login", true).commit(); } else { dbAdapter.logout(uuid, curTime); PreferenceUtil.getPreference(getApplication()).edit().putBoolean("login", false).commit(); } dbAdapter.close(); if (twitter != null) { TweetTask tTask = new TweetTask(twitter, isLogin); tTask.setOnTweetResultListener(this); String msg = PreferenceUtil.getServerMessage(getApplication()); msg = msg.replace("${client}", "@"+username+" ").replace("${date}", data).toString(); StatusUpdate su = new StatusUpdate(msg); su.setInReplyToStatusId(statusId); tTask.exec(su); } sendHtmlFromAssets("res_labnow.html"); iReader.close(); hostSocket.shutdownInput(); hostSocket.shutdownOutput(); hostSocket.close(); hostSocket = null; } else if (read.startsWith(CustomWebView.URL_TWEET)) { sendHtmlFromAssets("tweet_response.html"); } else { if (PreferenceUtil .existUser(getApplication(), read)) { if (PreferenceUtil.isDifferentDate(getApplication(), read + "loginlogin") || !PreferenceUtil.getPreference(getApplication()).getBoolean("login", false)) { sendCustomHtml(true); } else { sendCustomHtml(false); } } else { sendHtmlFromAssets("index.html"); } } } } } catch (IOException e) { Logger.e(TAG, e); } if (!Thread.currentThread().isInterrupted()) { Thread.currentThread().interrupt(); } } private void sendHtmlFromAssets(String fileName) { Logger.d(TAG, "sendHtmlFromAssets:"+fileName); String html = new HTMLBuilder().appendAssets(getAssets(), fileName).build(); Logger.d(TAG, html); sendMessage2Client(html); } private void sendCustomHtml(boolean isLogin) { Logger.d(TAG, "Custom html"); String loginHref = PreferenceUtil.getHttpRefererLogin(getApplication()); String logoutHref = PreferenceUtil.getHttpRefererLogout(getApplication()); String anchor = PreferenceUtil.getAnchor(getApplication()); if (TextUtils.isEmpty(anchor) || TextUtils.isEmpty(loginHref) || TextUtils.isEmpty(logoutHref)) { sendHtmlFromAssets("index.html"); } else { if (isLogin) { sendCustomHtml(loginHref+"&login=true", anchor+":?"); } else { sendCustomHtml(logoutHref+"&login=false", anchor+":?"); } } } private void sendCustomHtml(String href, String anchor) { HTMLBuilder builder = new HTMLBuilder().appendAssets(getAssets(), "template_head"); builder.appendBtn(CustomWebView.URL_TWEET+"name="+anchor+"&href="+href, anchor); sendMessage2Client(builder.appendAssets(getAssets(), "template_tail").build()); } private void sendMessage2Client(String message) { oPWriter.println(message); } private void showMessage(String message) { Message msg = new Message(); msg.what = WHAT_SHOWING_TOAST; msg.obj = message; mMessageHandler.sendMessage(msg); } @Override public void onPostedAll(boolean isLogin) { Thread.currentThread().interrupt(); } @Override public void onPosted(Status status, boolean isLogin) { } } private static class MessageHandler extends Handler { private WeakReference<ServerService> wRef; public MessageHandler(ServerService service) { wRef = new WeakReference<ServerService>(service); } @Override public void handleMessage(Message msg) { ServerService service = wRef.get(); if (service == null) { return; } switch (msg.what) { case WHAT_SHOWING_TOAST: service.showToast((String) msg.obj); break; } super.handleMessage(msg); } } @Override public void onDisabled() { finishServer(); } @Override public void onDisabling() { // finishServer(); } @Override public void onEnabling() { // finishServer(); } @Override public void onEnabled() { launchServer(); } @Override public void onUnknownState() { // finishServer(); } @Override public void onConnected(NetworkInfo info) { launchServer(); } @Override public void onConnecting(NetworkInfo info) { // finishServer(); } @Override public void onDisconnectingOrOther(NetworkInfo info) { finishServer(); } private synchronized void launchServer() { if (mServerSocket == null && mThread == null) { String ssid = CommonUtil.getCurrentSSID(getApplicationContext()); if (!TextUtils.isEmpty(ssid)) { servertPort = PreferenceUtil.getServerPortOnServer( getApplication(), ssid); mThread = new Thread(new OpenSocketWorker()); mThread.start(); } } } private synchronized void finishServer() { if (mThread != null) { mThread.interrupt(); mThread = null; } for(Thread th:accedptedRunningThreadList) { if (!th.isInterrupted()) { th.interrupt(); } } accedptedRunningThreadList.clear(); if (mServerSocket != null) { try { mServerSocket.close(); mServerSocket = null; } catch (IOException e) { Logger.e(TAG, e); } } } }