0

我想在PC和手机之间建立连接。PC作为客户端,PC端代码用C++或C编写。另一方面,手机作为服务器,手机端代码用Android编写。这两个设备通过 USB 电缆连接,它们用于相互通信,这意味着服务器(电话)没有固定的 IP。为了两个设备可以通信,我们必须在客户端进行端口转发(我猜)。我已经用Java实现了客户端(代码如下),但我对C++/C知之甚少,我不知道如何用C++/C实现端口转发,或者我不知道客户端的实现使用 C++/C,希望有人可以帮助我。

try {
    // how to realize sentence below with C++
    Runtime.getRuntime().exec("adb forward tcp:8081 tcp:8082");
    Thread.sleep(TIME_SLEEP);
} catch (Exception e) {
    e.printStackTrace();
}

Socket socket = null;
try {
    InetAddress serveraddr = null;
    serveraddr = InetAddress.getByName("127.0.0.1");
    socket = new Socket(serveraddr, 8081);      
} catch (UnknownHostException e1) {
    e1.printStackTrace();
} catch (Exception e2) {
    e2.printStackTrace();
}
4

1 回答 1

0

I've solve this problem. Solution contains two .h files and one cpp file. Codes list as below:

InitSock.h

#include <winsock2.h>
#include <stdlib.h> 
#include <conio.h> 
#include <stdio.h> 
#pragma comment(lib, "WS2_32")  // link to WS2_32.lib
class CInitSock     
{
public:
    CInitSock(BYTE minorVer = 2, BYTE majorVer = 2)
    {
        // init WS2_32.dll
        WSADATA wsaData;
        WORD sockVersion = MAKEWORD(minorVer, majorVer);
        if(::WSAStartup(sockVersion, &wsaData) != 0)
        {
            exit(0);
        }
    }
    ~CInitSock()
    {   
        ::WSACleanup(); 
    }
};

SocketDll.h

#pragma once 
#define DLL_EXPORT __declspec(dllexport)  
extern "C" DLL_EXPORT void startSocket(); 

SocketDll.cpp

#include "InitSock.h"
#include <stdio.h>
#include <iostream>  
#include <process.h>
using namespace std;

CInitSock initSock;     // init lib Winsock

#include "SocketDll.h" 

void startSocket() 
{ 
    // port forwarding(mapping)
    system("adb forward tcp:8081 tcp:8082");

    // new socket
    SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(s == INVALID_SOCKET)
    {
        printf(" Failed socket() /n");
        return;
    }

    sockaddr_in servAddr; 
    servAddr.sin_family = AF_INET;
    servAddr.sin_port = htons(8081);

    // set up ip
    servAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    if(::connect(s, (sockaddr*)&servAddr, sizeof(servAddr)) == -1)
    {
        printf(" Failed connect() /n");
        return;
    } else {
        cout << "connect successed!" << endl;
    }

    char buff[256];
    char szText[256] ;

    while(TRUE)
    {
        // send datas to server
        cin>>szText ;
        szText[255] = '/0';
        ::send(s, szText, strlen(szText), 0) ;

        // receiver datas from server
        int nRecv = ::recv(s, buff, 256, 0);
        if(nRecv > 0)
        {
            buff[nRecv] = '/0';
            printf("data received:%s/n", buff);
        }

    }

    // close socket
    ::closesocket(s); 
} 
于 2013-10-29T07:20:31.400 回答