Android与C++ 使用socket传输数据

1. 使用C++ 建立socket server监听

bool isBroadcastServerLanuch = false;
bool isTcpTlsServerLanuch = false;
int tcpSocketReceive_fd;
void *receiveCmdFromMobileApp(void *arg){
  int detachCode = pthread_detach(pthread_self());// 将状态改为unjoinable状态,确保资源的释放
  printf("receiveCmdFromMobileApp thread: detachCode = %d\n", detachCode);
  std::string send_content;
  tcpSocketReceive_fd = *(int *)arg;
  char buf[256];
  int n;
  while(((n = recv(tcpSocketReceive_fd , buf, 256, 0)) !=  0) && isWifiNetworkSecure){
    if(n == -1){
        perror("\t\t\tfail to receive command from mobile app!!!");
        continue;
    }

    std::string recv_content = buf;

    memset(buf,0,sizeof(buf));
    printf("receive content is : %s\n",recv_content.c_str());
    printf("buf content: %s\n", buf);
    
    //TODO something

    char* send_buff;
    const int len = send_content.length();
    send_buff = new char[len+1]{0};
    strcpy(send_buff,send_content.c_str());
    printf("will send buff is : \n%s\n",send_buff);

    n = send(tcpSocketReceive_fd , send_buff, len , 0);
    if( n == -1){
        perror("fail to send");
    }
  }
  if(n == 0){
      printf("the connect has been closed\n");
      if(close(tcpSocketReceive_fd) == -1){
          perror("fail to close");
      }
  }
  printf("thread end!\n");

  pthread_exit(0);
  return 0;
}

int tcpSocket_fd;
void *createSocketConnectionsForMobileApp(void *argv){
  int detachCode = pthread_detach(pthread_self());// 将状态改为unjoinable状态,确保资源的释放
  printf("start creat socket connection: detachCode= %d\n",detachCode);

  struct sockaddr_in sin;
  struct sockaddr_in cin;
  socklen_t len;
  int port = TCP_SOCKET_RECEIVE_IP_PORT; //6001
  bzero(&sin , sizeof(sin));

  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = INADDR_ANY;
  sin.sin_port = htons(port);

  if((tcpSocket_fd = socket(AF_INET,SOCK_STREAM,0)) == -1){
      perror("fail to create socket");
      pthread_exit(0);
      return 0;
  }
  int on = 1;
  if(setsockopt(tcpSocket_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0){
    perror("Unable to setsockopt");
    pthread_exit(0);
    return 0;
  }
  if(bind(tcpSocket_fd,(struct sockaddr *)&sin ,sizeof(sin) ) == -1){
      perror("fail to bind");
      pthread_exit(0);
      return 0;
  }

  if(listen(tcpSocket_fd,10) == -1){
      perror("fail to listen");
      pthread_exit(0);
      return 0;
  }
  printf("connect socket waiting.....\n");
  len = 1;
  while(1 && isWifiNetworkSecure){
      int c_fd;
      if((c_fd = accept(tcpSocket_fd,(struct sockaddr *)&cin, &len)) == -1){
          perror("fail to accept");
          continue;
      }
      printf("\t\t\thave client connect to server !!!!\n");
      if(isWifiNetworkSecure){
        pthread_t receiveCmdFromMobileAppAction;
        int receiveCmdFromMobileAppActionResult = pthread_create(&receiveCmdFromMobileAppAction, NULL, receiveCmdFromMobileApp,&c_fd);
        printf("\t%s: recieve command from mobile app. errorCode = %d\n", APP_TAG.c_str(), receiveCmdFromMobileAppActionResult);
      }else{
        printf("the network secure is false, not start receive thread.\n");
      }

  }
  if(close(tcpSocket_fd) == -1){
      perror("fail to close");
  }

  pthread_exit(0);
  return 0;
}
2. Android client code

import android.annotation.SuppressLint;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

class TCPHelper {
    private static final String TAG = "xxxx";
    private WifiManager.MulticastLock lock;
    private static TCPHelper instance = null;
    private Socket socket;
    private PrintWriter out;
    private InputStream is;

    static TCPHelper getInstance(){
        if(instance == null){
            instance = new TCPHelper();
        }
        return instance;
    }

    private TCPHelper() {
        Log.i(TAG,"udp helper initial");
    }

    private class ReadThread extends Thread {

        @SuppressLint("NewApi")
        @Override
        public void run() {
            try {
                is = socket.getInputStream();
                byte[] buffer = new byte[1024];
                int cnt = 0;
                while ((cnt = is.read(buffer))!=-1) {
                    try {
                        // read message
                        Log.d(TAG, "accept socket status:" + socket.isConnected());
                        String msg = new String(buffer, 0, cnt);
                        Log.d(TAG, "receive message:" + msg);
                        if (listener != null) {
                            listener.receive(msg);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.d(TAG, "Read message error!");
            }
        }
    }

    void connect(final String IpAddress, final int port) {
        Log.i(TAG, "connect");
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, " sync task");
                connectSync(IpAddress,port);
            }
        });
        Log.i(TAG, "AsyncTask over");
    }

    private void connectSync(String IpAddress,int port){
        Log.i(TAG, "Connecting");
        try {
            System.out.println("Client:Connecting");
            //Socket connect
            socket = new Socket(IpAddress, port);
            if (socket.isConnected()
                    && listener != null){
                listener.connected();
            }
            out = new PrintWriter(
                    new BufferedWriter(new OutputStreamWriter(
                            socket.getOutputStream())), true);
            //Read server message
            new Thread(new ReadThread()).start();
        } catch (UnknownHostException e1) {
            Log.i(TAG, "connect: unknown host");
            e1.printStackTrace();
        } catch (IOException e) {
            Log.i(TAG, "connect: io error");
            e.printStackTrace();
        }
    }
    // send a string
    void sendDataToServer(final String message) {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, " sync task for socket write");
                sendDataSync(message);
            }
        });

    }

    private void sendDataSync(String message){
        try {
            // OutputStream outputStream = socket.getOutputStream();
            Log.i(TAG,"send socket status = "+socket.isConnected());
            if (socket.isConnected()) {
                //   outputStream.write((message+"\n").getBytes());
                out.println(message);
                Log.i(TAG, "send a data!");
            }else {
                if (listener != null){
                    listener.disconnected();
                }
            }
            Log.i(TAG, "send a data over!");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void destroy() {
        if (lock != null){
            lock.release();
            lock = null;
        }
        if (out!=null){
            out.close();
            out = null;
        }
        if (is!=null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            is = null;
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            socket = null;
        }
        Log.i(TAG,"release socket");
        instance = null;
    }

    public interface TCPHelperListener{
        void connected();
        void disconnected();
        void receive(String data);
    }
    private TCPHelperListener listener = null;
    void setTCPHelperListener(TCPHelperListener listener){
        this.listener = listener;
    }
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值