最近導師要求我和另一個同學開發一個手機上課簽到應用,我負責客戶端和服務器之間的通信架構編寫和數據的存儲
本人大學四年只用過匯編和C/C++,因此對andriod開發還是一竅不通,花了一個星期寫出來了基本的通信功能
首先是服務器端的架構:
在網絡通信上主要有三類網絡通信線程,一是定時多播線程將同一局域網內的教師機ip廣播給所有學生機,由於一個AP支持的連接數不多,所以才使用定時多播。二是監聽線程,接受學生機的tcp連接然后new出簽到事務線程。三是事務線程,處理學生的簽到信息和返回簽到狀態,數據庫使用andriod自帶的Sqlite,由於會有大量事務線程,因此要做好線程同步問題。
1 //主線程主要代碼 2 wifiManager= (WifiManager) getSystemService(Context.WIFI_SERVICE); 3 4 mButton.setOnClickListener(new Button.OnClickListener(){ 5 @Override 6 public void onClick(View v){ 7 mEcho = (TextView)findViewById(R.id.client_text); 8 mEcho.setText("begin"); 9 10 //建立一個監聽線程 11 TCPListenThread tcpListenThread = new TCPListenThread(port); 12 tcpListenThread.start(); 13 /* 建立一個多播線程,要在監聽線程建立后才開始建立 */ 14 MulticastThread multicastThread = new MulticastThread(wifiManager); 15 multicastThread.start();
1 //多播線程,假設多播一百秒 2 try { 3 Log.i(TAG, "In MulticastThread.run()"); 4 InetAddress address = InetAddress.getByName(multiAdderss); 5 multicastSocket = new MulticastSocket(); 6 //multicast per second 7 for(int i = 0; i != 100; ++i){ 8 String msg = "I'm the teacher, my IP Address is?" + teacherIP; 9 byte[] buf = msg.getBytes(); 10 //Constructs a new DatagramPacket object to send data to the port aPort of the address host. 11 DatagramPacket packet=new DatagramPacket(buf,buf.length,address,port); 12 multicastSocket.send(packet); 13 Thread.sleep(1000); 14 } 15 }catch(UnknownHostException e){ 16 e.printStackTrace(); 17 } catch (IOException e) { 18 e.printStackTrace(); 19 } catch (InterruptedException e) { 20 e.printStackTrace(); 21 } 22 super.run();
1 //監聽線程 2 public void run(){ 3 Log.i(TAG, "In TCPListenThread.run()"); 4 try { 5 listenSocket = new ServerSocket(mPort); 6 while(true){ 7 CheckinSocket = listenSocket.accept(); 8 //將簽到邏輯交給checkinThread處理 9 CheckinThread checkinThread = new CheckinThread(CheckinSocket); 10 checkinThread.start(); 11 12 } 13 } catch (IOException e) { 14 e.printStackTrace(); 15 } 16 super.run(); 17 }
1 //事務線程主要代碼 2 public void run(){ 3 Log.i(TAG, "In CheckinThread.run()"); 4 5 try { 6 InputStreamReader input = new InputStreamReader( checkinSocket.getInputStream(),"UTF-8"); 7 8 char[] b = new char[1024]; 9 StringBuilder builder = new StringBuilder(); 10 int i; 11 while(( i = input.read(b)) != -1){ 12 builder.append(b,builder.length(),i); 13 } 14 String msg = builder.toString(); 15 Log.i(TAG, "In CheckinThread.run() msg:"+msg); 16 17 // writeIntoDB(msg);//將msg寫入數據庫 18 19 checkinSocket.close(); 20 } catch (IOException e) { 21 e.printStackTrace(); 22 } 23 super.run(); 24 }
經多台機子的測試,服務器能正常工作,但由於本人只有一個星期的andriod開發經驗,里面的代碼難免會有不足和bug,希望各位能指出,謝謝~~