C# PC客户端与Android服务端的Socket同步通信(USB)

需求:

      Android的apk获取手机信息,把结果发给PC client

注意地方:

     1.android默认手机端的IP为“127.0.0.1”

     2.要想联通PC与android手机的sokcet,一定要用adb forward 来作下端口转发才能连上socket.

       3.使用socket通信,需要在mainfest.xml中添加permission: android.permission.INTERNET

  1. Runtime.getRuntime().exec("adb forward tcp:12580 tcp:10086");     
  2.  Thread.sleep(3000);    

Android作为服务端:

  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.IOException;  
  4. import java.net.InetAddress;  
  5. import java.net.ServerSocket;  
  6. import java.net.Socket;  
  7.   
  8.   
  9. public class TcpConnect implements Runnable{  
  10.     private final  int SERVER_PORT = 10086;  
  11.     private ServerSocket mServerSocket;  
  12.     private Socket mClient;  
  13.     private String mDeviceId;  
  14.     private String mDeviceType;  
  15.     public TcpConnect(String aDeviceId, String aDeviceType){  
  16.         this.mDeviceId= aDeviceId;  
  17.         this.mDeviceType = aDeviceType;  
  18.         try {              
  19.             String ip = InetAddress.getLocalHost().getHostAddress();    
  20.             System.out.println("ip地址是: " + ip);  
  21.             //System.out.println(aDeviceId + "   型号: " + aDeviceType);  
  22.             mServerSocket = new ServerSocket(SERVER_PORT);  
  23.             System.out.println("TcpConnect" + "建立Socket");  
  24.         //  listen();  
  25.               
  26.         } catch (IOException e) {  
  27.             // TODO Auto-generated catch block  
  28.             //e.printStackTrace();  
  29.             System.out.println("TcpConnect" + e.getMessage());  
  30.         }         
  31.     }  
  32.       
  33.     public void listen(){  
  34.         while(true){              
  35.             try {  
  36.             mClient = mServerSocket.accept();     
  37.     //      Log.e("TcpConnect", "在积极的监听");  
  38.               
  39.         } catch (IOException e) {  
  40.             // TODO Auto-generated catch block  
  41.             //e1.printStackTrace();  
  42.             System.out.println("TcpConnect" + e.getMessage());  
  43.         }  
  44.         }  
  45.           
  46.     }  
  47.       
  48.   
  49.     @Override  
  50.     public void run() {  
  51.         // TODO Auto-generated method stub    
  52.     //  if(mClient.isConnected()){  
  53.         BufferedOutputStream out = null;      
  54.         System.out.println("TcpConnect" + "开始监听");  
  55.         while(true){  
  56.         try{                      
  57.         //  Log.e("TcpConnect", "开始监听");  
  58.             mClient = mServerSocket.accept();     
  59.         //  if(mClient.isConnected()){  
  60.             System.out.println("TcpConnect" + "检测到有连接");  
  61.             out = new BufferedOutputStream(mClient.getOutputStream());        
  62.             String recordStr = mDeviceId + "|" + mDeviceType;  
  63.             out.write(recordStr.getBytes("utf-8"));  
  64.     //      int length = recordStr.getBytes().length;         
  65.     //      byte[] b = recordStr.getBytes();      
  66.     //      out.writeInt(length);         
  67.     //      out.write(b);     
  68.             out.flush();  
  69.               
  70. //          Log.e("TcpConnect", recordStr);  
  71. //          out.flush();              
  72.     //      }  
  73.         }   catch(Exception e){           
  74.             System.out.println("TcpConnect" + e.getMessage());  
  75.           
  76.         }finally{  
  77.             if(out != null){  
  78.                 try {  
  79.                     out.close();  
  80.                 } catch (IOException e) {  
  81.                     // TODO Auto-generated catch block  
  82.                     System.out.println("TcpConnect" + e.getMessage());  
  83.                 }  
  84.                   
  85.             }  
  86.             if(mServerSocket != null){  
  87.                 try {  
  88.                     mServerSocket.close();  
  89.                 } catch (IOException e) {  
  90.                     // TODO Auto-generated catch block  
  91.                     System.out.println("TcpConnect" + e.getMessage());  
  92.                 }  
  93.             }  
  94.     //  }  
  95.         }  
  96.           
  97.           
  98.         }     
  99.     }  
  100.       
  101.       public static void main(String[] args){  
  102.           new Thread(new TcpConnect("2366578546946""T959")).start();  
  103.       }  
  104.       
  105.   
  106.     }  

C#作为客户端,在客户端进行绑定端口

[c-sharp] view plaincopy
  1. Process p = new Process(); //实例一个Process类,启动一个独立进程  
  2.                p.StartInfo.FileName = "cmd.exe"//设定程序名  
  3.                p.StartInfo.UseShellExecute = false//关闭Shell的使用  
  4.                p.StartInfo.RedirectStandardInput = true//重定向标准输入  
  5.                p.StartInfo.RedirectStandardOutput = true//重定向标准输出  
  6.                p.StartInfo.RedirectStandardError = true//重定向错误输出  
  7.                p.StartInfo.CreateNoWindow = true// 设置不显示窗口  
  8.                p.StartInfo.ErrorDialog = false;  
  9.                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;  
  10.                p.Start();  
  11.                p.StandardInput.WriteLine(@"adb forward tcp:12580 tcp:10086");  
  12.   
  13.   
  14.                //         Thread.Sleep(3000);     
  15.                SocketClient client = new SocketClient();  
  16.                MessageBox.Show("收到的数据为: " + client.listen());  

C#的Socket客户端

[c-sharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Net;  
  6. using System.Net.Sockets;  
  7.   
  8.   
  9. namespace PreInstaller.IO  
  10. {  
  11.     class SocketClient  
  12.     {  
  13.     
  14.   
  15.         public string listen()  
  16.         {            
  17.             Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
  18.             IPAddress myIP = IPAddress.Parse("127.0.0.1");  
  19.             IPEndPoint EPhost = new IPEndPoint(myIP, int.Parse("12580"));  
  20.             client.Connect(EPhost);            
  21.             byte[] t_data = new byte[1024];  
  22.             string data = null;  
  23.             int i = 0;  
  24.              while ((i = client.Receive(t_data)) != 0)  
  25.              {  
  26.                  data = Encoding.UTF8.GetString(t_data, 0, i);                        
  27.   
  28.              }  
  29.              client.Close();  
  30.              return data;               
  31.         }  
  32.     }  
  33. }  
原文地址:https://www.cnblogs.com/canphp/p/2833262.html