1个回答
展开全部
简单的写了一下,没有加注释,应该很好理解,满意的话请采纳
#include <stdio.h>
#include <sys/socket.h>
#include <pthread.h>
void *thread(void *st);
int main(int argc, char *argv[])
{
pthread_t tid;
int ret, fd;
struct sockaddr_in info;
fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd < 0)
goto socket_error;
{
int var = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &var, sizeof(var));;
}
info.sin_family = AF_INET;
info.sin_port = htons(80);
info.sin_addr.s_addr = 0;
ret = bind(fd, (void *)&info, sizeof(info));
if(ret)
goto bind_error;
ret = listen(fd, 10);
if(ret)
goto listen_error;
while(1)
{
clientfd = accept(fd, NULL, NULL);
pthread_create(&tid, NULL, thread, (void *)clientfd);
}
return 0;
socket_error:
printf("socket error!\n");
return -1;
bind_error:
printf("bind error!\n");
return -2;
lister_error:
printf("lister error!\n");
return -2;
}
void *thread(void *st)
{
int ret, rd;
char buf[BUFSIZE];
int clientfd = (int)st;
rd = read(clientfd, buf, sizeof(buf));
if(rd < 0)
{
printf("read error!\n")
return;;
}
write(clientfd, "shou dao!", 9);
close(clientfd);
}
#include <stdio.h>
#include <sys/socket.h>
#include <pthread.h>
void *thread(void *st);
int main(int argc, char *argv[])
{
pthread_t tid;
int ret, fd;
struct sockaddr_in info;
fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd < 0)
goto socket_error;
{
int var = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &var, sizeof(var));;
}
info.sin_family = AF_INET;
info.sin_port = htons(80);
info.sin_addr.s_addr = 0;
ret = bind(fd, (void *)&info, sizeof(info));
if(ret)
goto bind_error;
ret = listen(fd, 10);
if(ret)
goto listen_error;
while(1)
{
clientfd = accept(fd, NULL, NULL);
pthread_create(&tid, NULL, thread, (void *)clientfd);
}
return 0;
socket_error:
printf("socket error!\n");
return -1;
bind_error:
printf("bind error!\n");
return -2;
lister_error:
printf("lister error!\n");
return -2;
}
void *thread(void *st)
{
int ret, rd;
char buf[BUFSIZE];
int clientfd = (int)st;
rd = read(clientfd, buf, sizeof(buf));
if(rd < 0)
{
printf("read error!\n")
return;;
}
write(clientfd, "shou dao!", 9);
close(clientfd);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询