Program Examples:TCP IP:TCPIP Winsock Client/zh-hans

From SoftMC-Wiki
< Program Examples:TCP IP:TCPIP Winsock Client
Revision as of 08:36, 16 July 2017 by Chi (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
语言: English  • 中文(简体)‎

以下示例是以C语言编写的TCP / IP Windows套接字客户端。 此示例对应于TCP/IP TelNet Server示例。 要使用代码段,请将#define IP_ADDRESS“10.4.20.201”设置为正确的IP地址,并使用以下命令使用MinGW进行编译::

C:\> mingw32-gcc.exe tcp_client2.c -lws2_32

首先通过运行TCP/IP TelNet Server中显示的脚本,然后运行TCP / IP客户端,在MC中启动服务器。 客户端将收到从服务器发送的数据,发送数据设置MC变量x和y,查询变量的值并退出。

此示例基于MSDN中的“connect”示例: http://msdn.microsoft.com/en-us/library/windows/desktop/ms737625(v=vs.85).aspx

#ifndef UNICODE
#define UNICODE
#endif

#define WIN32_LEAN_AND_MEAN

#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>

// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

#define DEFAULT_BUFLEN 512


#define IP_ADDRESS  "10.4.20.201"
#define TELNET_PORT 6001


int main() {

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

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService; 

    int recvbuflen = DEFAULT_BUFLEN;
    //char *sendbuf = "Client: sending data test";
	char sendbuf[16];
    char recvbuf[DEFAULT_BUFLEN] = "";

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

    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        wprintf(L"socket failed with error: %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( IP_ADDRESS );
    clientService.sin_port = htons( TELNET_PORT );

    //----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
    if (iResult == SOCKET_ERROR) {
        wprintf(L"connect failed with error: %d\n", WSAGetLastError() );
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
  }

	Sleep(1000);
	
    // Receive until the peer closes the connection
   // do {

        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        if ( iResult > 0 )
		{
            wprintf(L"Bytes received: %d\n", iResult);
			printf("%s\r\n", recvbuf);
		}
        else if ( iResult == 0 )
            wprintf(L"Connection closed\n");
        else
            wprintf(L"recv failed with error: %d\n", WSAGetLastError());

   // } while( iResult > 0 );
	
	Sleep(1000);

    //----------------------
    // Send an initial buffer
	sprintf(sendbuf, "x 59\r\n");
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

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

	Sleep(1000);

	sprintf(sendbuf, "y 234\r\n");
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

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

	Sleep(1000);

	printf("Query the value of x:\n");
	sprintf(sendbuf, "x\r\n");
	memset(recvbuf, 0, 32);
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %d\n", iResult);
	
	iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
	if ( iResult > 0 )
	{
		printf("%s\n", recvbuf);
	}

	Sleep(1000);

	printf("Query the value of y:\n");
	sprintf(sendbuf, "y\r\n");
	memset(recvbuf, 0, 32);
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

	Sleep(200);
    printf("Bytes Sent: %d\n", iResult);
	
	iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
	if ( iResult > 0 )
	{
		printf("%s\n", recvbuf);
	}

	Sleep(1000);

	printf("Disconnecting...\n");
	sprintf(sendbuf, "quit\r\n");
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

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

	Sleep(1000);

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


    // close the socket
    iResult = closesocket(ConnectSocket);
    if (iResult == SOCKET_ERROR) {
        wprintf(L"close failed with error: %d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    WSACleanup();
    return 0;
}

程序输出

tcp client output.PNG

该示例对应于在GIT中的提交的SHA-1: 13fe83b3d3b75759cdd42b0db658148406f24b6d in GIT.


See Also