This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
zhangyang-libzt/test/dumb/tcpclient4.cpp
2017-04-20 13:39:46 -07:00

64 lines
1.5 KiB
C++

// TCP Client test program
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
int atoi(const char *str);
int close(int filedes);
#define MSG_SZ 128
int main(int argc , char *argv[])
{
if(argc < 3) {
printf("usage: client <addr> <port> <single|multiple> <n?>\n");
return 1;
}
int sock, port = atoi(argv[2]);
struct sockaddr_in server;
char message[MSG_SZ] , server_reply[MSG_SZ];
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1) {
printf("could not create socket");
}
server.sin_addr.s_addr = inet_addr(argv[1]);
server.sin_family = AF_INET;
server.sin_port = htons( port );
printf("connecting...\n");
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0) {
perror("connect failed. Error");
return 1;
}
printf("connected\n");
char *msg = (char*)"welcome to the machine!";
while(1)
{
// TX
if(send(sock, msg, strlen(msg), 0) < 0) {
printf("send failed");
return 1;
}
else {
printf("TX: %s\n", msg);
printf("len = %ld\n", strlen(msg));
int bytes_read = read(sock, server_reply, MSG_SZ);
if(bytes_read < 0)
printf("\tRX: Nothing\n");
else
printf("\tRX = (%d bytes): %s\n", bytes_read, server_reply);
}
}
close(sock);
return 0;
}