2 Star 1 Fork 0

李刚/socket

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
my_socket_thread.c 2.17 KB
Copy Edit Raw Blame History
李刚 authored 2018-03-24 16:43 . add my_socket_thread.c
/*********************************************************************************
* 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;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/ZuoKanYunQi/socket.git
git@gitee.com:ZuoKanYunQi/socket.git
ZuoKanYunQi
socket
socket
master

Search

0d507c66 1850385 C8b1a773 1850385