网络通信TCP编程实例代码

时间:2024-11-07 14:34:08

Makefile:

all:
gcc -o server server.c -lpthread
gcc -o client client.c clean:
rm server client

server.c:

/*TCP:
server.c
*/ #include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h> void *do_work(void *arg); int main(int argc,char *argv[])
{
int sockfd;
int ret; /*1.调用socket建立网络套接字*/
sockfd = socket(AF_INET,SOCK_STREAM,);
if(- == sockfd){
perror("socket server");
return -;
} /*2.填充服务器地址和端口号*/
struct sockaddr_in servaddr;
memset(&servaddr,,sizeof(servaddr));
servaddr.sin_family = AF_INET; //协议族
servaddr.sin_port = htons(); //端口号5001-65536
servaddr.sin_addr.s_addr = inet_addr("192.168.7.223"); //ip地址
socklen_t alen = sizeof(servaddr); /*3.调用bind绑定服务器地址和端口*/
ret = bind(sockfd,(struct sockaddr *)&servaddr,alen);
if(- == ret){
perror("bind");
return -;
} /*4.调用listen主动监听是否有客户连接*/
ret = listen(sockfd,);
if(- == ret){
perror("listen");
return -;
}
printf("servet init.d success...\n"); int newfd = -; //新的套接字描述符
char buf[] = {};
pthread_t tid; //新建线程ID while()
{
/*5.调用accept接受客户端连接*/
newfd = accept(sockfd,NULL,NULL);
if(newfd <= ){
continue;
}
printf("==>%d connect success..\n",newfd); /*为每个客户开辟一个线程去管理*/
ret = pthread_create(&tid,NULL,do_work,&newfd);
if( != ret){
perror("pthread_create failed\n");
break;
}
pthread_detach(tid);//设置为分离态,资源由系统自动回收 } /*7.关闭打开的网络套接字***/
close(sockfd);
close(newfd); return ;
} /*线程执行函数*/
void *do_work(void *arg)
{
int newfd = *(int *)arg;
int ret;
char buf[]; /*6.调用read/write读写网络文件*/
while()
{
memset(buf,,sizeof(buf));
ret = read(newfd,buf,sizeof(buf)-);
if(ret > ){
printf("recv data:%s\n",buf);
}
} pthread_exit(NULL);
}

client.c:

/*TCP:
client.c
*/ #include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h> int main(int argc,char *argv[])
{
int sockfd;
int ret;
char buf[] = {}; /*1.调用socket建立网络套接字*/
sockfd = socket(AF_INET,SOCK_STREAM,);
if(- == sockfd){
perror("socket server");
return -;
} /*2.填充服务器地址和端口号*/
struct sockaddr_in servaddr;
memset(&servaddr,,sizeof(servaddr));
servaddr.sin_family = AF_INET; //协议族
servaddr.sin_port = htons(); //端口号5001-65536
servaddr.sin_addr.s_addr = inet_addr("192.168.7.223"); //ip地址
socklen_t alen = sizeof(servaddr); /*3.调用connect连接服务器(根据ip地址和端口去连接)*/
ret = connect(sockfd,(struct sockaddr *)&servaddr,alen);
if(- == ret){
perror("connect");
return -;
}
printf("client connect success...\n"); /*4.调用read/write读写网络文件*/
while()
{
/*从终端获取信息*/
memset(buf,,sizeof(buf));
ret = read(,buf,sizeof(buf)-);
if(ret > ){ /*发送给服务器*/
write(sockfd,buf,ret);
}
} /*7.关闭打开的网络套接字***/
close(sockfd); return ;
}