转载:http://blog.csdn.net/li_wen01/article/details/52665505
工作中最近有使用到socket 向客户端同时发送和接收数据,因为是嵌入式linux设备,且要求只能同时一个客户端连接该端口。考虑到节省系统资源,只创建了两个线程分别实现服务端的收发数据。下面直接上代码,该代码为在PC机上程序,已作详细注释。
server.c
[objc] view
plain copy
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
#include
-
-
#define MAXLINE 256
-
#define PORT 6666
-
int listenfd;
-
int connfd;
-
pthread_t read_id, write_id;
-
-
-
-
-
-
void stop(int signo)
-
{
-
printf("stop
");
-
close(connfd);
-
close(listenfd);
-
_exit(0);
-
}
-
-
-
-
-
-
-
void signal_pipe(int signo)
-
{
-
pthread_kill(read_id,SIGQUIT);
-
pthread_join(read_id,NULL);
-
-
close(connfd);
-
printf("read pthread out
");
-
-
pthread_exit(0);
-
}
-
-
-
-
-
-
void pthread_out(int signo)
-
{
-
pthread_exit(0);
-
}
-
-
-
-
-
void* read_func(void* arg)
-
{
-
char readbuff[MAXLINE];
-
int n = 0;
-
int fd;
-
-
fd = *(int*)arg;
-
memset(&readbuff,0,sizeof(readbuff));
-
-
signal(SIGQUIT,pthread_out);
-
while(1)
-
{
-
n = recv(fd, readbuff, MAXLINE, 0);
-
if(n > 0)
-
{
-
printf("server recv data: %s
",readbuff);
-
}
-
};
-
}
-
-
-
-
void* write_func(void* arg)
-
{
-
char writebuff[MAXLINE];
-
char* write = "I am server";
-
unsigned char i = 0;
-
int num = 0;
-
int fd;
-
-
fd = *(int*)arg;
-
memset(&writebuff,0,sizeof(writebuff));
-
-
signal(SIGPIPE,signal_pipe);
-
while(1)
-
{
-
sleep(1);
-
send(fd,write,strlen(write)+1,0);
-