Socket通信-客户端

            WSADATA wsd;
	SOCKET sHost;
	SOCKADDR_IN servAddr;
	
	if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
		return -1;
	sHost = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (INVALID_SOCKET == sHost)
	{
		WSACleanup();
		return  -1;
	}

	servAddr.sin_family = AF_INET;
	servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	servAddr.sin_port = htons((short)4999);
	int nServAddlen = sizeof(servAddr);

	int nRetVal = connect(sHost, (LPSOCKADDR)&servAddr, sizeof(servAddr));
	if (SOCKET_ERROR == nRetVal)
	{
		closesocket(sHost);
		WSACleanup();
		return -1;
	}
	
	char SendBuf[SEND_BUF_SIZE] = {0};
	memcpy(SendBuf, chCmd, strlen(chCmd));
	nRetVal = send(sHost, SendBuf, strlen(SendBuf), 0);
	if (SOCKET_ERROR == nRetVal)
	{
		closesocket(sHost);
		WSACleanup();
		return -1;
	}		
	closesocket(sHost);
	WSACleanup();
posted @ 2020-09-22 16:33  Mojito2020  阅读(106)  评论(0编辑  收藏  举报