linux TCP客户端程序事例
时间:2014-05-17 10:59 来源:linux.it.net.cn 作者:it
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <errno.h>
#include <net/if.h>
#include <arpa/inet.h>
main()
{
char *send_message ="abcdefg123456";
struct sockaddr_in addr;
int sockLen,sock,j;
char chCmd[500] = {0};//max 500;
char *sou = NULL;
char ch[50]={0};
for(;;)
{
sock=socket (AF_INET, SOCK_STREAM, 0);
if (sock == -1)
{
printf ("create sock error\n");
return -1;
}
memset (&addr, 0, sizeof(struct sockaddr_in));
addr.sin_addr.s_addr = inet_addr("192.168.0.18");
addr.sin_family = AF_INET;
addr.sin_port = htons (8080);
if ( connect(sock, (struct sockaddr*)&addr, sizeof(addr)) != -1 )
{
if((sockLen=send(sock,send_message,strlen(send_message),0))==-1)
{
printf("send error\n");
goto innererror;
}
while(1)
{
if((sockLen=recv(sock,chCmd,sizeof(chCmd),0))>0) //lsq
{
printf("chcmd=%s\n",chCmd);
}
else
{
if (!sockLen)
{
printf("%d client close!\n",sockLen);
goto innererror;//client closed!!!!!!
}
}
}
}
innererror:
close( sock );
printf("error\n");
sleep(5);
}
}
(责任编辑:IT)
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <syslog.h> #include <sys/types.h> #include <sys/time.h> #include <sys/socket.h> #include <time.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> #include <errno.h> #include <net/if.h> #include <arpa/inet.h> main() { char *send_message ="abcdefg123456"; struct sockaddr_in addr; int sockLen,sock,j; char chCmd[500] = {0};//max 500; char *sou = NULL; char ch[50]={0}; for(;;) { sock=socket (AF_INET, SOCK_STREAM, 0); if (sock == -1) { printf ("create sock error\n"); return -1; } memset (&addr, 0, sizeof(struct sockaddr_in)); addr.sin_addr.s_addr = inet_addr("192.168.0.18"); addr.sin_family = AF_INET; addr.sin_port = htons (8080); if ( connect(sock, (struct sockaddr*)&addr, sizeof(addr)) != -1 ) { if((sockLen=send(sock,send_message,strlen(send_message),0))==-1) { printf("send error\n"); goto innererror; } while(1) { if((sockLen=recv(sock,chCmd,sizeof(chCmd),0))>0) //lsq { printf("chcmd=%s\n",chCmd); } else { if (!sockLen) { printf("%d client close!\n",sockLen); goto innererror;//client closed!!!!!! } } } } innererror: close( sock ); printf("error\n"); sleep(5); } } (责任编辑:IT) |