发送数据时Socket send()函数失败

时间:2014-03-11 12:43:03

标签: java c++ sockets send serversocket

所以我编写了一个客户端/服务器程序,其中客户端是用C ++编写的,服务器是用Java编写的。当我尝试将数据发送到java端时,send()函数失败并返回-1。我不知道问题是什么。

见客户方:

    int main(){

    string address = "127.0.0.1";
    sockaddr_in socketInfo;//declare struct object
    SOCKET socketClient;
    WSAData network;
    int errorNum;//networking functions return integer values that represent the success of the call to the function
    errorNum = WSAStartup(MAKEWORD(2, 2), &network);
    if (errorNum == 0){
        socketInfo.sin_family = AF_INET;//set family to ipv4
        socketInfo.sin_port = htons(6897);//set port to connect to and convert to network byte order htons
        errorNum = inet_pton(socketInfo.sin_family, "127.0.0.1", &socketInfo.sin_addr);
        socketClient = socket(socketInfo.sin_family, SOCK_STREAM, IPPROTO_TCP);//creates a socket
        if (socketClient != INVALID_SOCKET){
            errorNum = connect(socketClient, (sockaddr*)&socketInfo, sizeof(socketInfo));
            if (errorNum != SOCKET_ERROR){
                cout << "Connected to Java Application!" << endl;
                int num = 152;
                cout << "Trying to send..." << endl;
                const char* buff = (const char*)(num);
                errorNum = send(socketClient, buff, sizeof(buff), 0);

                if (errorNum != SOCKET_ERROR)
                    cout << "sent with success " << errorNum << endl;
                else
                    cout << "Failed to send " << errorNum << endl;
                closesocket(socketClient);
            }
            else{
                cout << "Failed to connect" << endl;
                closesocket(socketClient);
            }
        }
        else
            cout << "Socket creation failed!" << endl;
    }//end if
    else
        cout << "WSA startup failed" << endl;

    WSACleanup();

    //thread t1(getStroke, VK_SPACE);
    //thread t2(getStroke, VK_ESCAPE);

    //t1.join();
    //t2.join(); 

    system("pause");
    return 0;
}

继承服务器方面:

    try {
        server = new ServerSocket(6897);
    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    new Thread(new Runnable() {
        public void run() {
            try {
                System.out.println("Waiting on C++ Application...");
                connection = server.accept();
                System.out.println("Connected to C++ Application!");
                setupStreams();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        private void setupStreams() {
            // TODO Auto-generated method stub
            try {
                input = new DataInputStream(connection.getInputStream());
                int data = 0;
                System.out.println("Waiting for data...");
                data = input.read();
                System.out.println("Data recieved " + data);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }).start();

2 个答案:

答案 0 :(得分:0)

首先检查IPv4地址(在CMD中使用ipconfig),你应该在Thread中执行while循环,以便每次检查收到的数据。

private void setupStreams() {
            // TODO Auto-generated method stub
           while (!Thread.currentThread().isInterrupted())// you have to add this line
            try {
                input = new DataInputStream(connection.getInputStream());
                String data = ""; //use string is better than int
                System.out.println("Waiting for data...");
                data = input.readUTF();// readUTF for string types
                System.out.println("Data recieved " + data);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

并且不要忘记从客户端

以字符串形式发送数据

答案 1 :(得分:0)

您在send()函数中使用了无效的强制转换。

int num = 152; cout << "Trying to send..." << endl; const char* buff = (const char*)(num);

在上面的代码中,您必须使用& num,如下面的代码,

const char* buff = (const char*)(&num);

而且,对于'endianness',使用htonl()要好得多。 所以,我认为这段代码会更好

cout << "Trying to send..." << endl;

int num = 152;
int net_num = htonl(num);
send(sock, (const char*)&net_num, sizeof(int), 0);