// char chBuff[BUFF_SIZE] = "This is clinet init data,\n这是初始化数据。\n";
// function // connecting the TCP server static bool StartClient(int argc, char *argv[]) { while (argc < 2) { printf("Warning: input IP and port, process exit.\n"); printf("-----------------------------------\n\n"); return false; } printf("IP = %s TCP port = %s\n", argv[1], argv[2]); unsigned int nSocket = 0; if( (-1 == (nSocket = socket(AF_INET, SOCK_STREAM, 0))) ) { printf("Error: create socket error, process exit.\n"); printf("-----------------------------------\n\n"); return false; } struct sockaddr_in ServerAddr; memset(&ServerAddr, 0, sizeof(struct sockaddr_in)); ServerAddr.sin_family = AF_INET; ServerAddr.sin_addr.s_addr = ( inet_addr(argv[1]) ); ServerAddr.sin_port = htons( atoi(argv[2]) ); unsigned int uLen = sizeof(struct sockaddr_in); if ( -1 == (connect(nSocket, (struct sockaddr *) &ServerAddr, uLen)) ) { printf("Error: connect TCP server failed, process exit.\n"); printf("-----------------------------------\n\n"); return false; }
// receive and send data int uData = 0; unsigned int nDataLen = 0; while (1) { if ( -1 == (nDataLen = send(nSocket, chBuff, strlen(chBuff), 0)) ) { printf("Error: send data failed.\n"); printf("-----------------------------------\n\n"); continue; } else { printf("Send data OK data is : %s [%d bytes]\n", chBuff, nDataLen); memset(chBuff, 0, sizeof(chBuff)); uData ++; //strcpy(chBuff, "wenxy"); sprintf(chBuff, "%d", uData); //memcpy(chBuff, &(char)uData, sizeof(uData)); } sleep(2);
}
if (nSocket) { close(nSocket); } return true; }
/* * Input: IP address, port */ int main(int argc, char *argv[]) { printf("Run ...\n"); if (StartClient(argc, argv)) { printf("connect TCP server OK\n"); }