转自:http://blog.csdn.net/linweidong/article/details/6273507

 

需求:

      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

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

 

Android作为服务import java.io.BufferedInputStream;import java.io.BufferedOutputStream;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;


public class TcpConnect implements Runnable{
    private final  int SERVER_PORT = 10086;
    private ServerSocket mServerSocket;
    private Socket mClient;
    private String mDeviceId;
    private String mDeviceType;
    public TcpConnect(String aDeviceId, String aDeviceType){
        this.mDeviceId= aDeviceId;
        this.mDeviceType = aDeviceType;
        try {             
            String ip = InetAddress.getLocalHost().getHostAddress();  
            System.out.println("ip地址是: " + ip);
            //System.out.println(aDeviceId + "   型号: " + aDeviceType);
            mServerSocket = new ServerSocket(SERVER_PORT);
            System.out.println("TcpConnect" + "建立Socket");
          // listen();
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            System.out.println("TcpConnect" + e.getMessage());
        }        
    }
    
    public void listen(){
        while(true){            
            try {
              mClient = mServerSocket.accept();    
           // Log.e("TcpConnect", "在积极的监听");
          } catch (IOException e) {
              // TODO Auto-generated catch block
              //e1.printStackTrace();
              System.out.println("TcpConnect" + e.getMessage());
          }
        }
        
    }
    

    @Override
    public void run() {
        // TODO Auto-generated method stub    
      // if(mClient.isConnected()){
        BufferedOutputStream out = null;    
        System.out.println("TcpConnect" + "开始监听");
        while(true){
        try{                    
          // Log.e("TcpConnect", "开始监听");
            mClient = mServerSocket.accept();    
          // if(mClient.isConnected()){
            System.out.println("TcpConnect" + "检测到有连接");
            out = new BufferedOutputStream(mClient.getOutputStream());        
            String recordStr = mDeviceId + "|" + mDeviceType;
            out.write(recordStr.getBytes("utf-8"));
         // int length = recordStr.getBytes().length;        
         // byte[] b = recordStr.getBytes();    
         // out.writeInt(length);        
         // out.write(b);    
            out.flush();
            // Log.e("TcpConnect", recordStr);
        // out.flush();            
         // }
        } catch(Exception e){
      System.out.println(
"TcpConnect" + e.getMessage()); }finally{ if(out != null){ try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("TcpConnect" + e.getMessage()); } } if(mServerSocket != null){ try { mServerSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("TcpConnect" + e.getMessage()); } } // } } } } public static void main(String[] args){ new Thread(new TcpConnect("2366578546946", "T959")).start(); } }

 

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

 Process p = new Process(); //实例一个Process类,启动一个独立进程
                p.StartInfo.FileName = "cmd.exe"; //设定程序名
                p.StartInfo.UseShellExecute = false; //关闭Shell的使用
                p.StartInfo.RedirectStandardInput = true; //重定向标准输入
                p.StartInfo.RedirectStandardOutput = true; //重定向标准输出
                p.StartInfo.RedirectStandardError = true; //重定向错误输出
                p.StartInfo.CreateNoWindow = true; // 设置不显示窗口
                p.StartInfo.ErrorDialog = false;
                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                p.Start();
                p.StandardInput.WriteLine(@"adb forward tcp:12580 tcp:10086");


                //         Thread.Sleep(3000);   
                SocketClient client = new SocketClient();
                MessageBox.Show("收到的数据为: " + client.listen());

 

C#的Socket客户端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;


namespace PreInstaller.IO
{
    class SocketClient
    {
  

        public string listen()
        {          
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress myIP = IPAddress.Parse("127.0.0.1");
            IPEndPoint EPhost = new IPEndPoint(myIP, int.Parse("12580"));
            client.Connect(EPhost);          
            byte[] t_data = new byte[1024];
            string data = null;
            int i = 0;
             while ((i = client.Receive(t_data)) != 0)
             {
                 data = Encoding.UTF8.GetString(t_data, 0, i);                      

             }
             client.Close();
             return data;             
        }
    }
}

 

posted on 2014-09-23 06:39  HalfmanG2  阅读(5941)  评论(0编辑  收藏  举报