C++连接到 C# 服务器的套接字

发布于 2024-12-23 08:26:09 字数 3314 浏览 1 评论 0原文

我有一个使用 TcpClient 和流用 C# 编写的服务器。当我尝试使用 Winsock 连接到它并使用 C++ 应用程序接收数据时,我可以接收数据,但它有数据,但它还显示一堆其他数据。顺便说一句,我正在使用 cout 打印到缓冲区到控制台。

如果您想查看服务器应发送的内容,请转至 http://onenetworks.us:12345 。服务器将向您发送一个字符串。对我来说,它发送“16READY”,这就是我试图让我的客户只阅读的内容。

连接时显示的内容。

这是我的代码,我从 MSDN 页面复制了一个工作代码文件。

    #define WIN32_LEAN_AND_MEAN

#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <iostream>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "12345"

int main() {

    //----------------------
    // Declare and initialize variables.
    WSADATA wsaData;
    int iResult;

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService; 

    char *sendbuf = "";
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;

    //----------------------
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        printf("Error at socket(): %ld\n", WSAGetLastError() );
        WSACleanup();
        return 1;
    }

    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr( "199.168.139.14" );
    clientService.sin_port = htons( 12345 );

    //----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
    if ( iResult == SOCKET_ERROR) {
        closesocket (ConnectSocket);
        printf("Unable to connect to server: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    // Send an initial buffer
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        printf("send failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    // Receive until the peer closes the connection
    do {

        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        std::cout << recvbuf <<std::endl;
        if ( iResult > 0 )
            printf("Bytes received: %d\n", iResult);
        else if ( iResult == 0 )
            printf("Connection closed\n");
        else
            printf("recv failed: %d\n", WSAGetLastError());

    } while(iResult > 0);

    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
    std::cin.ignore();
    //return 0;
}

I have a server written in C# using a TcpClient and streams. When I try to connect to it and receive data with a C++ application using Winsock, I can receive the data but it has the data but it also displays a bunch of other data. By the way I'm printing to buffer to the console using cout.

If you want to see what the server is supposed to send, go to http://onenetworks.us:12345. There the server will send you a string. For me it sends "16READY" Which is what I'm trying to get my client to only read.

What is displayed when you connect.

Here's my code, I copied a working code file off of the MSDN page.

    #define WIN32_LEAN_AND_MEAN

#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <iostream>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "12345"

int main() {

    //----------------------
    // Declare and initialize variables.
    WSADATA wsaData;
    int iResult;

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService; 

    char *sendbuf = "";
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;

    //----------------------
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        printf("Error at socket(): %ld\n", WSAGetLastError() );
        WSACleanup();
        return 1;
    }

    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr( "199.168.139.14" );
    clientService.sin_port = htons( 12345 );

    //----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
    if ( iResult == SOCKET_ERROR) {
        closesocket (ConnectSocket);
        printf("Unable to connect to server: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    // Send an initial buffer
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        printf("send failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    // Receive until the peer closes the connection
    do {

        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        std::cout << recvbuf <<std::endl;
        if ( iResult > 0 )
            printf("Bytes received: %d\n", iResult);
        else if ( iResult == 0 )
            printf("Connection closed\n");
        else
            printf("recv failed: %d\n", WSAGetLastError());

    } while(iResult > 0);

    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
    std::cin.ignore();
    //return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苦行僧 2024-12-30 08:26:09

仅打印接收到的字符,而不打印发送的整个缓冲区。 iResult 将包含接收到的数据的长度:

    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    if ( iResult > 0 )
    {
        printf("Bytes received: %d\n", iResult);
        std::cout << std::string(recvbuf, recvbuf+iResult) <<std::endl;

    }
    else if ( iResult == 0 )
        printf("Connection closed\n");
    else
        printf("recv failed: %d\n", WSAGetLastError());

Print only the characters received, not the entire buffer posted. iResult will contain the length of the data received:

    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    if ( iResult > 0 )
    {
        printf("Bytes received: %d\n", iResult);
        std::cout << std::string(recvbuf, recvbuf+iResult) <<std::endl;

    }
    else if ( iResult == 0 )
        printf("Connection closed\n");
    else
        printf("recv failed: %d\n", WSAGetLastError());
瀞厅☆埖开 2024-12-30 08:26:09

缓冲区的长度设置为 DEFAULT_BUFLEN,因此您通过套接字接收到的任何内容都具有该长度。您可以循环遍历它的每个字符,直到找到值 0(或“\0”)。

The length of your buffer is set to DEFAULT_BUFLEN, so whatever you receive through the socket has that length. you can loop through every char of it, until a value of 0 (or '\0') is found.

演出会有结束 2024-12-30 08:26:09

你可以这样做:(

...
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
recvbuf[iResult] = 0; // add this to zero terminate the receive buffer
std::cout << recvbuf <<std::endl;
...

当然它假设 iResult 小于 DEFAULT_BUFLEN)

You could do something like this:

...
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
recvbuf[iResult] = 0; // add this to zero terminate the receive buffer
std::cout << recvbuf <<std::endl;
...

(of course it assumes iResult is lesser than DEFAULT_BUFLEN)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文