Android Socket With NodeJS

MainActivity

package com.buzz.beaconlib;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import android.os.StrictMode;
import android.os.Handler;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Message;
import android.widget.Button;
import android.view.View;
//import android.util.Log;
import android.widget.ArrayAdapter;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;

public class MainActivity extends ActionBarActivity {

    private static String HOST = "192.168.0.106";
    private static int PORT = 2397;
    static String ActiveCMD = "";

    Socket socket;
    Thread socketMsgThread;
    Handler inHandler;
    Handler resultHandler;
    InputStream in;
    ObjectMapper objectMapper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle bundle = getIntent().getExtras();
        HOST = bundle.getString("HOST");
        PORT = Integer.parseInt(bundle.getString("PORT"));

        StrictMode.setThreadPolicy(
                new StrictMode
                        .ThreadPolicy
                        .Builder()
                        .detectDiskReads()
                        .detectDiskWrites()
                        .detectNetwork()
                        .penaltyLog()
                        .build());

        StrictMode.setVmPolicy(
                new StrictMode
                        .VmPolicy
                        .Builder()
                        .detectLeakedSqlLiteObjects()
                        .detectLeakedClosableObjects()
                        .penaltyLog()
                        .penaltyDeath()
                        .build());

        final TextView tvHost = (TextView) findViewById(R.id.tvHost);
        tvHost.setText(HOST);

        final TextView tvPort = (TextView) findViewById(R.id.tvPort);
        tvPort.setText(String.valueOf(PORT));

        try {
            socket = new Socket(HOST, PORT);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            ShowDialog(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            ShowDialog(e.getMessage());
        }

        final Button btnGetBeaconInfo = (Button) findViewById(R.id.btnGetBeaconInfo);
        final Button btnGetSysparams = (Button) findViewById(R.id.btnGetSysparams);
        final Button btnGetUserInfo = (Button) findViewById(R.id.btnGetUserInfo);
        final Button btnAddSyslog = (Button) findViewById(R.id.btnAddSyslog);
        final Button btnAddKey = (Button) findViewById(R.id.btnAddKey);
        final Button btnOpen = (Button) findViewById(R.id.btnOpen);
        final Button btnClose = (Button) findViewById(R.id.btnClose);

        btnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    writer.write(GlobalConst.CMD_OPEN);
                    writer.flush();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                }

                ActiveCMD = "06";
            }
        });

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    writer.write(GlobalConst.CMD_CLOSE);
                    writer.flush();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                }

                ActiveCMD = "07";
            }
        });

        btnGetBeaconInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    writer.write(GlobalConst.CMD_GET_BEACON_INFO);
                    writer.flush();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                }

                ActiveCMD = "01";
            }
        });

        btnGetSysparams.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    writer.write(GlobalConst.CMD_GET_SYS_PARAMS);
                    writer.flush();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                }

                ActiveCMD = "02";
            }
        });

        btnGetUserInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    writer.write(GlobalConst.CMD_GET_USER_INFO);
                    writer.flush();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                }

                ActiveCMD = "03";
            }
        });

        btnAddSyslog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    writer.write(GlobalConst.CMD_ADD_SYS_LOG);
                    writer.flush();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                }

                ActiveCMD = "04";
            }
        });

        btnAddKey.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    writer.write(GlobalConst.CMD_ADD_KEY);
                    writer.flush();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    ShowDialog(e.getMessage());
                }

                ActiveCMD = "05";
            }
        });

        objectMapper = new ObjectMapper();

        resultHandler = new Handler() {
            public void handleMessage(Message msg) {
                List<String> ds = new ArrayList<String>();
                switch (msg.what) {
                    case 1:
                        BeaconInfo beaconInfo = (BeaconInfo) msg.obj;
                        ds.add(beaconInfo.getBeacon().get(0).toString());
                        for (triggers t : beaconInfo.getTriggers()) {
                            ds.add(t.toString());
                        }
                        for (contents c : beaconInfo.getContents()) {
                            ds.add(c.toString());
                        }
                        ShowResult(ds);
                        break;

                    case 2:
                        Sysparams[] sysparamsList = (Sysparams[]) msg.obj;
                        for (Sysparams sp : sysparamsList) {
                            ds.add(sp.toString());
                        }
                        ShowResult(ds);
                        break;

                    case 3:
                        UserInfo[] userInfoList = (UserInfo[]) msg.obj;
                        ds.add(userInfoList[0].toString());
                        ShowResult(ds);
                        break;

                    case 4:
                        ShowResult(ds);
                        break;
                }
            }
        };

        inHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        TextView tvJsonData = (TextView) findViewById(R.id.tvJsonData);
                        tvJsonData.setText(msg.obj.toString());

                        switch (ActiveCMD) {
                            case "01":
                                try {
                                    BeaconInfo beaconInfo = objectMapper.readValue(msg.obj.toString(), BeaconInfo.class);
                                    Message message = new Message();
                                    message.what = 1;
                                    message.obj = beaconInfo;
                                    resultHandler.sendMessage(message);
                                } catch (IOException ex) {
                                    ShowDialog(ex.toString());
                                    return;
                                }
                                break;

                            case "02":
                                try {
                                    Sysparams[] SysparamsList = objectMapper.readValue(msg.obj.toString(), Sysparams[].class);
                                    Message message = new Message();
                                    message.what = 2;
                                    message.obj = SysparamsList;
                                    resultHandler.sendMessage(message);
                                } catch (IOException ex) {
                                    ShowDialog(ex.toString());
                                    return;
                                }
                                break;

                            case "03":
                                try {
                                    UserInfo[] userInfoList = objectMapper.readValue(msg.obj.toString(), UserInfo[].class);
                                    Message message = new Message();
                                    message.what = 3;
                                    message.obj = userInfoList;
                                    resultHandler.sendMessage(message);
                                } catch (IOException ex) {
                                    ShowDialog(ex.toString());
                                    return;
                                }
                                break;

                            default:
                                Message message = new Message();
                                message.what = 4;
                                resultHandler.sendMessage(message);
                                break;
                        }
                        break;
                    default:
                        break;
                }
            }
        };

        try {
            in = socket.getInputStream();
        } catch (Exception ex) {
            return;
        }
        socketMsgThread = new Thread(runnable);
        socketMsgThread.start();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            String line = "";
            while (true) {
                try {
                    byte[] temp = new byte[10240];// 默认最带为256
                    int size = 0;
                    while ((size = in.read(temp)) > 0) {
                        // -1表示文件结尾
                        byte[] res = new byte[size];// 默认最带为256
                        System.arraycopy(temp, 0, res, 0, size);
                        for (int i = 0; i < size; i++) {
                            line += (char) res[i];
                        }

                        Message message = new Message();
                        message.what = 1;
                        message.obj = line;
                        inHandler.sendMessage(message);
                        line = "";
                    }
                } catch (Exception ex) {
                    return;
                }
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void ShowResult(List<String> ds){
        ListView lvResult = (ListView) findViewById(R.id.lvResult);
        lvResult.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,ds));
    }

    private void ShowDialog(String msg) {
        new AlertDialog
            .Builder(this)
            .setTitle("notification")
            .setMessage(msg)
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();
    }
}

core.js

var net=require(‘net‘);
var mysql=require(‘./mysqlpool.js‘);
var client=require(‘./doorclient.js‘);
var fileserver=require(‘./fileserver.js‘);
function execute_command(socket, command, args) {
    switch(command){
      case "90":
        client.open();
        break;

      case "91":
        client.close();
        break;

      case "01":
        mysql.getBeaconInfo(socket,args);
        break;

      case "02":
        mysql.getSysparams(socket);
        break;

      case "03":
        mysql.getUserInfo(socket,args);
        break;

      case "04":
        mysql.addSyslog(socket,args);
        break;

      case "05":
        mysql.addKey(socket,args);
    }
};

var s = net.createServer(function(socket) {
    console.log(‘server connected‘);

    socket.on(‘data‘, function(d) {
      data = d.toString(‘utf8‘).trim();
      var cmd_re = /^(\d{2})+[ ]*(.*)/g;
      cmd_match = cmd_re.exec(data)
      if (cmd_match) {
        var command = cmd_match[1];
        var args = cmd_match[2];
        console.log(command+" "+args);
        execute_command(socket, command, args);
      }
    });

    socket.on(‘end‘, function() {
      console.log(‘server disconnected‘);
    });

    socket.on(‘error‘, function (ex) {
      console.log("ignoring exception: " + ex);
    });

});
s.listen(2397,‘192.168.0.106‘);
console.log(‘listen on server port:2397...‘);
时间: 2024-11-08 20:43:37

Android Socket With NodeJS的相关文章

Android socket 使用PrintWriter和BufferedReader发送和接收出现乱码问题解决

项目中用到了Android和C++的通信,选择了用socket 发送字符的方式,一开始使用的代码是: socket=new Socket(); InetSocketAddress isa = new InetSocketAddress(IP_STR, port); socket.connect(isa, 100); PrintWriter out=new PrintWriter(socket.getOutputStream(),true); BufferedReader recvBuf=new

Android Socket 发送广播包的那些坑

Socket广播包经常被用于局域网内的两台设备之间互相发现和消息传递,在Android应用开发过程中,也经常会遇到这样的需求,例如:两台Android设备之间.Android与手环等智能硬件之间.Android与Windows电脑之间等等. 本文主要介绍在Android中使用Socket开发广播包程序时需要注意的编程事项,以及解决方法. 首先给出一段Android发送广播包的示例代码: DatagramSocket socket = new DatagramSocket(8000); socke

android socket 网络数据传输

原文:http://blog.sina.com.cn/s/blog_726233070100nqw7.html 讲解一下android socket ,包括获取数据包,拆包,解包的过程. 有时候应用程序需要从网络上收发一些数据,软件的底层是用socket实习的,android操作系统的内核是linux,开发语言是java,刚好数据存储结构和以c构建的服务器大小头是相反的,所以取到c做的服务器数据时,需要转换一下数据的大小头.这里也一并讲解. 首先是socket //实例化一个socket(指定服

Android Socket编程学习笔记

通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄.在Internet上的主机一般运行了多个服务软件,同时提供几种服务.每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务. 网络上的两个程序通过一个双向的通讯连接实现数据的交换,这个双向链路的一端称为一个Socket.Socket通常用来实现客户方和服务方的连接.Socket是TCP/IP协议的一个十分流行的编程界面,一个Socket由一个IP地址和一个端口号唯一确定. 在java中,Socke

Android Socket简单测试

这里是将pc作为server,设备作为客户端. Server端代码: public static final String SERVERIP = "192.168.0.2"; public static final int SERVERPORT = 51706; public void run() { try { System.out.println("S: Connecting..."); ServerSocket serverSocket = new Serve

Android Socket编程

花了大概两天的时间,终于把Android的Socket编程给整明白了.抽空和大家分享一下: Socket Programming on Android Socket 编程基础知识: 主要分服务器端编程和客户端编程. 服务器端编程步骤: 1: 创建服务器端套接字并绑定到一个端口上(0-1023是系统预留的,最好大约1024) 2: 套接字设置监听模式等待连接请求 3: 接受连接请求后进行通信 4: 返回,等待赢一个连接请求 客户端编程步骤: 1: 创建客户端套接字(指定服务器端IP地址与端口号) 

Protobuf实现Android Socket通讯开发教程

本节为您介绍Protobuf实现Android Socket通讯开发教程,因此,我们需要先了理一下protobuf 是什么? Protocol buffers是一种编码方法构造的一种有效而可扩展的格式的数据. 谷歌使用其内部几乎RPC协议和文件格式的所有协议缓冲区. protobuf 适用的语言 正宗(Google 自己内部用的)的protobuf支持三种语言:Java .c++和Pyton,很遗憾的是并不支持.Net 或者 Lua 等语言,但社区的力量是不容忽视的,由于protobuf确实比J

Android必备:Android Socket编程的了解与学习整理

看这里:Android必备:Android Socket编程的了解与学习整理 最近学习Android的过程中,由于项目.业务等因素影响,服务端通过Socket进行通信,于是开始学习Socket编程,之前的开发中,很少涉及此 方面的知识学习,本篇就来简单的整理一下,通过Android客户端进行Socket登录的demo,来进行Adnroid Socket编程的学习. 在开始学习之前,先来了解一下Socket,以下内容来自百度百科: 通常也称作"套接字",用于描述IP地址和端口,是一个通信

Android Socket 通信

Android socket 通信 安卓编写Socket客户端,实现连接Socket服务端通信. 创建Socket连接并获取服务端数据 先创建几个全局变量吧 private BufferedWriter writer = null; Socket socket; 创建Socket // 填好IPV4的IP地址和端口,服务端会提供,问服务端要 socket = new Socket("192.168.1.156", 1234); // 下面三句照抄就行 writer = new Buff