Android App未连接到C ++本地服务器

时间:2017-10-20 23:07:15

标签: java android c++ sockets

我想让我的Android应用程序连接到运行在同一网络上的计算机上的C ++服务器,代码在Java中工作,在我自己的PC上,与Android设备在同一网络上。我在清单文件中包含了ACCESS_NETWORK_STATE权限。

C ++服务器正好适用于我目前正在进行的测试,但这里是代码:

#include <iostream>
#include <WS2tcpip.h>
#pragma comment (lib, "ws2_32.lib")

using namespace std;

int main() {
    // Variables
    const int PORT = 54000;
    const int BUFFER_SIZE = 4096;

    SOCKET serverSock, clientSock;
    sockaddr_in hint, client;
    WSADATA wsData;
    WORD version = MAKEWORD(2, 2);
    int wsOk, clientSize;
    char host[NI_MAXHOST]; // Client remote name
    char port[NI_MAXSERV]; // Client port
    char buffer[BUFFER_SIZE]; // Buffer to send and receive

    // Init winsock
    wsOk = WSAStartup(version, &wsData);

    if (wsOk != 0) {
        cerr << "Can't initialise winsock!" << endl;
        return 0;
    }

    // Create a socket
    serverSock = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSock == INVALID_SOCKET) {
        cerr << "Can't create server socket!" << endl;
        return 0;
    }

    // Bind socket to ip address and port
    hint.sin_family = AF_INET;
    hint.sin_port = htons(PORT);
    hint.sin_addr.S_un.S_addr = INADDR_ANY;

    bind(serverSock, (sockaddr*)&hint, sizeof(hint));

    // Tell winsock the socket is for listening
    listen(serverSock, SOMAXCONN);

    // Wait for connection
    clientSize = sizeof(client);
    clientSock = accept(serverSock, (sockaddr*)&client, &clientSize);

    if (clientSock == INVALID_SOCKET) {
        cerr << "Can't create client socket!" << endl;
        return 0;
    }

    ZeroMemory(host, NI_MAXHOST);
    ZeroMemory(port, NI_MAXSERV);

    if (getnameinfo((sockaddr*)&client, clientSize, host, NI_MAXHOST, port, NI_MAXSERV, 0) == 0) {
        cout << host << " connected on port " << port << endl;
    } else {
        inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
        cout << host << " connected on port " << ntohs(client.sin_port) << endl;
    }

    // Close listening socket
    closesocket(serverSock);

    // While loop: accept and echo message back to client
    while (true) {
        ZeroMemory(buffer, BUFFER_SIZE);

        // Wait for client to send data
        int bytesReceived = recv(clientSock, buffer, BUFFER_SIZE, 0);
        if (bytesReceived == SOCKET_ERROR) {
            cerr << "Error in recv()" << endl;
            continue;
        }
        else if (bytesReceived == 0) {
            cout << "Client disconnected" << endl;
            continue;
        }

        // Echo message back to client
        send(clientSock, buffer, bytesReceived + 1, 0);
    }

    // Close socket
    closesocket(clientSock);

    // Cleanup winsock
    WSACleanup();

    return EXIT_SUCCESS;
}

这是我用来管理服务器连接的类:

package com.networktest;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

public class Server {

    private String ip, message;
    private int port;
    private Socket socket;
    private DataInputStream in;
    private DataOutputStream out;

    public Server(String ip, int port) {
        this.setIp(ip);
        this.setPort(port);
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getIp() {
        return this.ip;
    }

    public int getPort() {
        return this.port;
    }

    public String getMessageString() {
        return this.message;
    }

    public boolean getMessage() {
        try {
            this.message = in.readUTF();
        } catch (Exception e) {
            System.out.println("There was an error while receiving a message from the server.");
            return false;
        }

        return true;
    }

    public boolean connect() {
        // Make socket connection to server
        try {
            socket = new Socket(this.ip, this.port);
        } catch (Exception e) {
            System.out.println("There was an error making the socket.");
            close();
            return false;
        }

        // Get the io streams for the server
        try {
            in = new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
        } catch (Exception e) {
            System.out.println("There was an error getting the i/o streams.");
            close();
            return false;
        }

        // Try send a test message
        sendMessage("Test message");

        return true;
    }

    public boolean sendMessage(String message) {
        this.message = message;
        try {
            out.writeUTF(this.message);
        } catch (Exception e) {
            System.out.println("There was an error sending a message to the server.");
            close();
            return false;
        }

        return true;
    }

    public void close() {
        if (socket == null) return; // Only try to close the socket if it exists
        try {
            socket.close();
        } catch (Exception e) {
            System.out.println("There was an error while closing the socket.");
            return;
        }

        if (in == null || out == null) return; // Only try to close if they exist
        try {
            in.close();
            out.close();
        } catch (Exception e) {
            System.out.println("There was an error while closing the i/o streams.");
            return;
        }

        return;
    }
}

最后这里是我创建Server对象的地方,注意这是在onClick上的按钮上运行的函数。

public void tryConnect(View v) {
    final String IP = "10.0.0.21";
    final int PORT = 54000;


    Server server = new Server(IP, PORT);
    if (server.connect()) {
        System.out.println("Connected");
    }
}

0 个答案:

没有答案
相关问题