#include "tcpsed.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <arpa/inet.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <pthread.h>
int socketfd;
void tcp_stophandler(int signum)
{
runcond = 0;
}
void quit(int signum)
{
close(socketfd);
printf("Bye~Bye!
");
pthread_exit(NULL);
}
void *pth_read(void *arg)
{
int runcond = 1;
int result;
char pth_buf[BUFFSIZE];
while(runcond)
{
if(0 > (result = read(socketfd,pth_buf,BUFFSIZE - 1)))
{
fprintf(stderr,"Read Error:%s
",strerror(errno));
}
pth_buf[result] = ' ';
printf("%s
",pth_buf);
}
pthread_exit(NULL);
}
void *tcppacketsend(void *arg)
{
runcond = 1;
struct sockaddr_in server_addr;
char buf[BUFFSIZE] = {0};
int connfd;
pthread_t tid;
TCP_send_arg_t *send_arg = (TCP_send_arg_t *)arg;
memset(&server_addr,0,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons((*send_arg).tcp_port);
server_addr.sin_addr.s_addr = inet_addr((*send_arg).tcpserver_addr);
if(-1 == (socketfd = socket(AF_INET,SOCK_STREAM,0)))
{
fprintf(stderr,"Socket Error:%s
",strerror(errno));
pthread_exit(NULL);
}
if(-1 == (connfd = connect(socketfd,(struct sockaddr*)&server_addr,sizeof(server_addr))))
{
fprintf(stderr,"Connect Error:%s
",strerror(errno));
pthread_exit(NULL);
}
printf("You can use "Ctrl + D" to quit.
");
if(SIG_ERR == signal(SIGUSR1,quit))
{
fprintf(stderr,"Can't set SIGUSR1 signal action!
");
pthread_exit(NULL);
}
if(0 != pthread_create(&tid,NULL,(void *)pth_read,(void *)buf))
{
fprintf(stderr,"Create pthread Error:%s
",strerror(errno));
pthread_exit(NULL);
}
while(NULL != (fgets(buf,BUFFSIZE,stdin)))
{
write(socketfd,buf,strlen(buf) - 1);
}
pthread_cancel(tid);
pthread_exit(NULL);
}