Android与C++ 使用socket传输数据
程序员文章站
2022-03-02 15:33:19
...
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;
}
}
上一篇: JPA之联合主键[复合主键]
推荐阅读
-
Android 模拟器(JAVA)与C++ socket 通讯 分享
-
C/C++中CJSON的使用(创建与解析JSON数据)
-
Python使用socket实现组播与发送二进制数据
-
python使用socket高效传输视频数据帧(连续发送图片)
-
android接口中json数据的传输中使用gzip压缩
-
android接口中json数据的传输中使用gzip压缩
-
Android 之 多线程与Socket联合使用案例
-
Android使用Intent传输数据
-
Android Linux Socket 数据传输错误
-
C语言与Python平台通过socket建立结构型方式数据传输通信(使用struct.pack())