简体   繁体   English

通过TCP与android(socket客户端)和c ++(socket服务器)连接

[英]conect android(socket client) with c++(socket server) via TCP

i have an implementation to do in a college project, and i dont know how to avchive it!. 我有一个大学项目要做的实现,我不知道该怎么做! my problem its like the title say, conect android with c++ via sockets. 我的问题就好像标题说的那样,通过套接字用c ++连接android。

c++ must manage at least a pair of sockets clients (android Devices) or more. c ++必须至少管理一对套接字客户端(Android设备)或更多。 so i try ... 所以我尝试...

#include <iostream>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>

using namespace std;

int main()
{
    int client, server;
    int portnum = 1500;
    bool isExit = false;
    int bufsize = 1024;
    char buffer[bufsize];

    struct sockaddr_in server_addr;
    socklen_t size;

    //init socekt

    client = socket(AF_INET, SOCK_STREAM, 0);

    if(client < 0){
        cout << "Error Estableciendo la conexion" << endl;
    }

    cout <<"server Socket conexion creada" << endl;

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htons(INADDR_ANY);
    server_addr.sin_port = htons(portnum);


    //biding soket

    if(bind(client,(struct sockaddr*)&server_addr,sizeof(server_addr)) < 0){
        cout << "Error Biding Socket" << endl;
        exit(1);
    }

    size= sizeof(server_addr);
    cout << "buscando clientes" << endl;

    //escuchando sokets

    listen(client,1);

    //accept client

    server = accept(client, (struct sockaddr*)&server_addr, &size);

    if(server < 0){
        cout<< "Error al Aceptar" << endl;
        exit(1);
    }

    while(server >0){
        strcpy(buffer,"server conectado---\n");
        send(server,buffer,bufsize,0);

        cout <<"conectado con el cliente" << endl;
        cout << "Ingresad # paara terminar la conexion" << endl;

        cout <<"client: ";
        do{
            recv(server,buffer,bufsize,0);
            cout << "buffer" << " ";
            if(*buffer == '#'){
                *buffer = '*';
                isExit=true;
            }
        }while(*buffer != '*');

        do{
            cout << "\n server: ";
            do{
                cin >> buffer;
                send(server,buffer,bufsize,0);
                if(*buffer == '#'){
                    send(server,buffer,bufsize,0);
                    *buffer = '*';
                    isExit=true;
                }
            }while(*buffer != '*');

            cout << "Client: ";

            do{
                recv(server,buffer,bufsize,0);
                cout << buffer << " ";
                if(*buffer == '#'){
                    *buffer = '*';
                    isExit = true;
                }
            }while(*buffer != '*');
        }while(isExit);

        cout << "Conection Terminated..." << endl;
        cout << "Goodbye..." << endl;
        isExit =false;
        exit(1);
    }
    close(client);
    return 0;
}

to listen every conection (please if you see bad logic in my code let me know it and what i need to do to fix it) 听每个连接(请如果您在我的代码中看到错误的逻辑,请让我知道它以及解决该问题所需做的事情)

and in android i make something like this in a class that its called from an activity only for testing... 在android中,我在一个类中做了这样的事情,该类只能从测试活动中调用...

import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Socktest {

    public void prueba() {
        try {
            Socket sock = new Socket("127.0.0.1",1234);

            // Your Java Code Verbatim:
            BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String test = br.readLine();

            System.out.println(test);
            sock.close();
        } catch (Exception ex) {
            System.out.println(ex.getCause().toString());
        }
    }
}

(please if you see bad logic let me knowit because i want to learn more from my failures) (请让我知道错误的逻辑,因为我想从失败中学习更多)

and the server goes fine when i compiled, its standing by to recive a new conection but when a luch the android activity and i run the "conection class" it says access denied, i am working on linux mint if that afect... 当我编译服务器时,服务器运行良好,等待新的连接,但是当出现android活动并运行“连接类”时,它说访问被拒绝,如果那样的话,我正在Linux Mint上工作...

i am going to be gratfull with you coments, suggestions and advices. 我将对您的评论,建议和意见感到满意。

Socket sock = new Socket("127.0.0.1",1234); this line is your problem right here, 127.0.0.1 is the local loop IP, its actually an IP address that maps to the device the code is on, so your android client is never connecting to the machine where the c++ code is running, instead what you need to do is find the IP address of the machine your c++ code is running on then change 127.0.0.1 to that IP address. 这行是您的问题所在, 127.0.0.1是本地循环IP,它实际上是一个IP地址,该IP地址映射到代码所在的设备,因此您的android客户端永远不会连接到运行c ++代码的计算机,您需要做的是找到正在运行c ++代码的计算机的IP地址,然后将127.0.0.1更改为该IP地址。

If you're mobile is connected to a wifi router to which your c++ server is connected to, then this IP address will be the local IP address, and everything is simple 如果您的手机已连接到与c ++服务器相连的wifi路由器,则此IP地址将是本地IP地址,一切都很简单

If you're mobile is connected to some mobile network, and your server is on a different network, then you need to find out the IP address of your machine exposed to the world (depending on Internet service providers configuration you might have an IP address that remains static, or an IP address that changes every time your connection to the ISP server resets) You can find your machines exposed IP address by going to websites like http://whatismyipaddress.com/ , then if your machine is behind a router, you need to do port forwarding (in this case forward your port 1234 to your machines local IP address) you can take a look at this guide to understand how to do that. 如果您的移动设备已连接到某个移动网络,并且您的服务器位于其他网络上,则需要找出暴露给外界的计算机的IP地址(取决于Internet服务提供商的配置,您可能拥有IP地址保持静态,或者IP地址在每次与ISP服务器的连接每次重置时都会更改)。您可以通过访问http://whatismyipaddress.com/等网站来查找计算机的IP地址,如果您的计算机位于路由器后面, ,您需要进行端口转发(在这种情况下,将端口1234转发到计算机的本地IP地址),您可以查看本指南以了解如何执行此操作。

So to avoid the complexity in the 2nd step I advise you to connect your mobile and your server in same local network (ie your LAN) using a wifi router. 因此,为避免第二步的复杂性,我建议您使用wifi路由器将移动设备和服务器连接到同一局域网(即LAN)中。

Ways to find the IP address of your machine: 查找机器IP地址的方法:

In linux based machines just open a terminal and type ifconfig and look at eth0 your IP address will be right after inet addr: , for example like this inet addr:10.99.123.23 在基于Linux的计算机上,只需打开一个终端并输入ifconfig并查看eth0您的IP地址将在inet addr: ,例如这样的inet addr:10.99.123.23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM