Android and PC terminals synchronize through LAN files

  • 2021-09-16 08:12:15
  • OfStack

This article shares the specific codes of Android and PC through LAN file synchronization for your reference, the specific contents are as follows


public class FileOptions {
   public String name;
   public String path;
   public long size;
}
 
//Activity
public class MainActivity extends Activity {
   private TextView tvMsg;
   private EditText logShow, filePath;
   private Handler handler;
   private SocketManager socketManager;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout. activity_main);
      
      tvMsg = (TextView)findViewById(R.id. tvMsg);
      logShow = (EditText)findViewById(R.id. log_show);
      handler = new Handler(){
         @Override
         public void handleMessage(Message msg) {
           switch(msg. what){
           case 0:
              SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss" );
              logShow.append( "\n[" + format.format(new Date()) + "]" + msg.obj .toString());
              break;
           case 1:
              tvMsg.setText( " Please visit PC Terminal input IP : " + GetIpAddress() + "  Port :" + msg.obj .toString());
              break;
           case 2:
             Toast. makeText(getApplicationContext(), msg.obj.toString(), Toast. LENGTH_SHORT).show();
              break;
           }
        }
      };
      socketManager = new SocketManager( handler);
   }
   @Override
   protected void onDestroy() {
      super.onDestroy();
      System. exit(0);
   }
   public String GetIpAddress() {  
     WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE );  
     WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
     int i = wifiInfo.getIpAddress();
     return (i & 0xFF) + "." +  
       ((i >> 8 ) & 0xFF) + "." +  
       ((i >> 16 ) & 0xFF)+ "." +  
        ((i >> 24 ) & 0xFF );  
   }  
}
 
//socket Management 
public class SocketManager {
   private static final String FILE_PATH= "/glass";
   private static final String TAG = "SocketManager";
   private ServerSocket server;
   private Handler handler = null;
   private List<FileOptions> fileList;
 
   public SocketManager(Handler handler) {
      this. handler = handler;
      int port = 9999;
      while (port > 9000) {
         try {
           server = new ServerSocket(port);
           break;
        } catch (Exception e) {
           port--;
        }
      }
      SendMessage(1, port);
      Thread receiveFileThread = new Thread( new Runnable() {
         @Override
         public void run() {
           while ( true) { //  Receive files 
              ReceiveFile();
           }
        }
      });
      receiveFileThread.start();
   }
 
   void SendMessage( int what, Object obj) {
      if ( handler != null) {
        Message. obtain( handler, what, obj).sendToTarget();
      }
   }
 
   //  Receive files 
   void ReceiveFile() {
      Socket socketPC= null;
      try {
        GetAllFiles();
        socketPC = server.accept();
        InetAddress netAddr = socketPC.getInetAddress();
        String ipaddr = netAddr.getHostAddress();
        Log. w( TAG, ipaddr);
        OutputStream outputStream = socketPC.getOutputStream();
        JSONArray jsonArr= new JSONArray();
         for( int i=0;i< fileList.size();i++){
           try {
              JSONObject jsonObj= new JSONObject();
              jsonObj.put( "name", fileList.get(i). name);
              jsonObj.put( "path", fileList.get(i). path);
              jsonObj.put( "size", fileList.get(i). size);
              jsonArr.put(jsonObj);
           } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           }
        }
        
        String sendStr=jsonArr.toString();
         byte[] sendBuf=sendStr.getBytes( "GB2312");
        outputStream.write(sendBuf, 0, sendBuf. length);
        outputStream.flush();
        SendMessage(0, "  Send file index complete " );
        outputStream.close();
        socketPC.close();
        
         for( int i=0;i< fileList.size();i++){
           Socket fileSendSocket = server.accept();
           File fsend= new File( fileList.get(i). path);
           FileInputStream fis= new FileInputStream(fsend);
           OutputStream fos = fileSendSocket.getOutputStream();
           byte[] buf = new byte[1024];
           while ( true) { 
           int read = 0; 
           if (fis != null) { 
             read = fis.read(buf); 
           } 
           if (read == -1) { 
             break; 
           } 
           fos.write(buf,0,read); 
         }
           fos.flush();
           SendMessage(0, fileList.get(i). name+ "-- File transfer complete " );
           fis.close();
           fos.close();
           fileSendSocket.close();
        }
        
      } catch (IOException e) {
         // TODO Auto-generated catch block
        e.printStackTrace();
      }
   }
 
   public void SendFile(ArrayList<String> fileName, ArrayList<String> path,
        String ipAddress, int port) {
      try {
         for ( int i = 0; i < fileName.size(); i++) {
           Socket name = new Socket(ipAddress, port);
           OutputStream outputName = name.getOutputStream();
           OutputStreamWriter outputWriter = new OutputStreamWriter(
                outputName);
           BufferedWriter bwName = new BufferedWriter(outputWriter);
           bwName.write(fileName.get(i));
           bwName.close();
           outputWriter.close();
           outputName.close();
           name.close();
           SendMessage(0, " Sending " + fileName.get(i));
 
           Socket data = new Socket(ipAddress, port);
           OutputStream outputData = data.getOutputStream();
           FileInputStream fileInput = new FileInputStream(path.get(i));
           int size = -1;
           byte[] buffer = new byte[1024];
           while ((size = fileInput.read(buffer, 0, 1024)) != -1) {
              outputData.write(buffer, 0, size);
           }
           outputData.close();
           fileInput.close();
           data.close();
           SendMessage(0, fileName.get(i) + "  Send complete " );
        }
        SendMessage(0, " All files sent complete " );
      } catch (Exception e) {
        SendMessage(0, " Send error :\n" + e.getMessage());
      }
   }
   // To be optimized 
   private void GetAllFiles(){
      fileList= new ArrayList<FileOptions>();
      File rootPath= new File(Environment.getExternalStorageDirectory().getPath()+ FILE_PATH);
      File[] files = rootPath.listFiles(); //  List all files 
      for( int i=0;i<files. length;i++){
         if(files[i].isFile()){
           FileOptions fp= new FileOptions();
           fp. name=files[i].getName();
           fp. path=files[i].getPath();
           fp. size=files[i].length();
           fileList.add(fp);
        }
      }
   }
}

The PC end is written in VS2005. Json format data is used for data communication. The main usage is: in the same LAN, open the PC and Android programs, enter correctly in the PC program editing box according to the IP address and port prompted by Android, and click the link to synchronize the files under the relevant folders under the root directory of sd card to PC.


//PC End main source code 
// Data transmission thread 
DWORD WINAPI RecvThread(LPVOID lpParameter)
{
   SOCKET recvSocket = (SOCKET)lpParameter;
    int ret = 0,strLen=0;
    char recvBuffer[MAX_LEN],*pRecvAllData;
   Json::Reader reader;
   Json::Value jsonArr;
   
    while ( true )
   {
       /*
      
      */
      pRecvAllData=( char *)malloc(MAX_LEN);
       while ((ret = recv(recvSocket, recvBuffer, MAX_LEN, 0))>0){
         strLen+=ret;
         pRecvAllData=( char *)realloc(pRecvAllData,strLen);
         memcpy(pRecvAllData+strLen-ret,recvBuffer,ret);
      };
      
       if (!reader.parse(pRecvAllData, jsonArr)){
         Sleep(1000);
          continue ;
      }
       int jsonSize = jsonArr.size();
      CString strItem;
      fileList.RemoveAll();
       for (int j = 0; j < jsonSize; ++j) 
      { 
         std::string name = jsonArr[j][ "name" ].asString();
         std::string path = jsonArr[j][ "path" ].asString();
          int size = jsonArr[j][ "size" ].asInt();
         strItem.Format(TEXT( "%d" ), j+1);
         pFileRecvDlg->m_fileListCtrl.InsertItem(j,strItem.GetBuffer(0));
         pFileRecvDlg->m_fileListCtrl.SetItemText(j,0,strItem.GetBuffer(0));
         strItem=name.c_str();
         fileStr filest;
         filest.name=name;
         filest.size=size;
         fileList.AddTail(filest);
         pFileRecvDlg->m_fileListCtrl.SetItemText(j,1,strItem.GetBuffer(0));
      }
      free(pRecvAllData);
      closesocket(recvSocket);
 
      CRect rect;
      pFileRecvDlg->GetClientRect(&rect);
      pFileRecvDlg->ClientToScreen(rect);
       if (!pProgressDlg->IsWindowVisible()){
         pProgressDlg->ShowWindow(SW_SHOW);
      }
      pProgressDlg->SetWindowPos(NULL,rect.left+100,rect.top+100,0,0,SWP_NOSIZE);
      pFileRecvDlg->GetDlgItem(IDC_BUTTON_CONNECT)->EnableWindow(FALSE);
       //  Send file name 
       for (int i=0;i<jsonSize;i++){
         SOCKET nameSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
          int ret = connect(nameSocket,( struct sockaddr*)&ServerAddr, sizeof (ServerAddr));
          if ( ret == SOCKET_ERROR ){
            AfxMessageBox(_T( "connect  Failure  "));
         } else {
         }
         FILE *fp;
          int tempCount=0;
         fileStr flst=fileList.GetAt(fileList.FindIndex(i));
         fopen_s(&fp,flst.name.c_str(), "wb+" );
         
         pProgressDlg->setFile(flst.name,flst.size);
          while ((ret = recv(nameSocket, recvBuffer, MAX_LEN, 0))!=0){
            fwrite(recvBuffer, sizeof (char ),ret,fp);
            tempCount+=ret;
            pProgressDlg->updateProgress(tempCount);
         }
         _fcloseall( );
         closesocket(nameSocket);
      }
      pFileRecvDlg->GetDlgItem(IDC_BUTTON_CONNECT)->EnableWindow(TRUE);
      pProgressDlg->ShowWindow(SW_HIDE);
   }
    return 0;
}
// Response function of connection button 
void CGlassFileRecvDlg::OnBnClickedButtonConnect()
{
    // TODO:  Add control notification handler code here 
    if (UpdateData()){
      BYTE nField0,nField1,nField2,nField3;
      m_IpAddrCtrl.GetAddress(nField0,nField1,nField2,nField3);
      WSADATA Ws;
      SOCKET CientSocket;
       int Ret = 0;
       int AddrLen = 0;
      HANDLE hThread = NULL;
       char SendBuffer[MAX_PATH];
 
       //Init Windows Socket
       if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )
      {
          return ;
      }
       //Create Socket
      CientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
       if ( CientSocket == INVALID_SOCKET )
      {
         MessageBox(_T( "socket  Failed to create  " ));
          return ;
      }
 
       char strAddr[50],tempStr[10];
      memset(strAddr,0, sizeof (strAddr));
      memset(tempStr,0, sizeof (tempStr));
      itoa(nField0,tempStr,10);
      strcat(strAddr,tempStr);
      strcat(strAddr, "." );
      itoa(nField1,tempStr,10);
      strcat(strAddr,tempStr);
      strcat(strAddr, "." );
      itoa(nField2,tempStr,10);
      strcat(strAddr,tempStr);
      strcat(strAddr, "." );
      itoa(nField3,tempStr,10);
      strcat(strAddr,tempStr);
 
      ServerAddr.sin_family = AF_INET;
      ServerAddr.sin_addr.s_addr = inet_addr(strAddr);
      ServerAddr.sin_port = htons(m_port);
      memset(ServerAddr.sin_zero, 0x00, 8);
 
      Ret = connect(CientSocket,( struct sockaddr*)&ServerAddr, sizeof (ServerAddr));
       if ( Ret == SOCKET_ERROR ){
         MessageBox(_T( "connect  Failure  "));
          return ;
      } else {
         HANDLE hThread = CreateThread(NULL, 0, RecvThread, (LPVOID)CientSocket, 0, NULL);
          if ( hThread == NULL ){
            MessageBox(_T( "  Failed to create thread  "));
             return ;
         }
         CloseHandle(hThread);
      }
   }
}

Source code download address is: android end and PC end file synchronization


Related articles: