Fetch the repository succeeded.
/*********************************************************************************
* Copyright: (C) 2018 ligang<2820724771@qq.com>
* All rights reserved.
*
* Filename: my_socket_thread.c
* Description: This file
*
* Version: 1.0.0(03/24/2018)
* Author: ligang <2820724771@qq.com>
* ChangeLog: 1, Release initial version on "03/24/2018 03:07:58 PM"
*
********************************************************************************/
#include<string.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h> //结构体sockaddr所需头文件
#include<errno.h>
#include <pthread.h>
#define PORT 8555
void *thread_worker(void * arg);
int main(int argc,char **argv)
{
int serv_fd;
struct sockaddr_in serv_addr;
serv_fd = socket(AF_INET,SOCK_STREAM,0);
if(serv_fd == -1)
{
printf("socket is failure :%s\n",strerror(errno));
return -1;
}
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);//自动获取本机ip地址
printf("listen port is %d\n",PORT);
if(bind(serv_fd,(const struct sockaddr*)&serv_addr,sizeof(serv_addr))==-1)
{
printf("bind is failure :%s\n",strerror(errno));
return -1;
}
if(listen(serv_fd,5)==-1)
{
printf("listen is failure :%s\n",strerror(errno));
return -1;
}
while(1)
{
pthread_t tid;
int new_fd;
printf(" begin to accept!!! \n");
new_fd = accept(serv_fd,NULL,NULL);
if(new_fd<0)
{
printf("accept is fail :%s",strerror(errno));
return -2;
}
pthread_create(&tid,NULL,thread_worker,(void*)new_fd);
}
close(serv_fd);
}
void *thread_worker(void * arg)
{
char buf[1024];
int fd = (int)arg;
printf("fd is[%d]\n",fd);
memset(buf,0,sizeof(buf));
read(fd,buf,sizeof(buf));
printf("read %s from client\n",buf);
write(fd,"welcome",7);
sleep(1);
close(fd);
return NULL;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。