TCP客户端
#include "stdio.h"
#include "pthread.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "arpa/inet.h"
#include "netinet/in.h"
#include "string.h"
pthread_t write_th,read_th;
int sock_service,sock_client;
struct sockaddr_in service_addr={0};
void * sock_write(void *p)
{
while(1)
{
char buf[1024];
fgets(buf,sizeof(buf),stdin);
write(sock_service,buf,strlen(buf));//发送消息
if(strcmp(buf, "exit") == 0)
{
break;//退出循环
}
}
close(sock_client);
close(sock_service);
pthread_cancel(write_th);
pthread_cancel(read_th);
}
void * sock_read(void *p)
{
while(1)
{
char buf[1024] = {0};
read(sock_service, buf, sizeof(buf));//阻塞,,等待客户端发来消
if(strcmp(buf, "exit") == 0||strcmp(buf,"")==0)
{
break;//退出循环
}
printf("receive msg:%s\n", buf);//打印消息
}
close(sock_service);
close(sock_client);
pthread_cancel(write_th);
pthread_cancel(read_th);
}
void create_sock(char *addr,int port)
{
sock_service = socket(AF_INET,SOCK_STREAM,0);//创建套接字
service_addr.sin_family =AF_INET; //IPV4
service_addr.sin_port = htons(port);//转大端字节序
service_addr.sin_addr.s_addr = inet_addr(addr);
connect(sock_service,(struct sockaddr *)&service_addr,sizeof(service_addr));
pthread_create(&write_th,NULL,sock_write,NULL);
pthread_create(&read_th,NULL,sock_read,NULL);
pthread_join(write_th,NULL);
pthread_join(read_th,NULL);
}
int main(int argc,char *argv[])
{
create_sock(argv[1],atoi(argv[2]));
return 0;
}
TCP服务端
#include "stdio.h"
#include "pthread.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "arpa/inet.h"
#include "netinet/in.h"
#include "string.h"
pthread_t write_th,read_th;
int sock_service,sock_client;
struct sockaddr_in service_addr={0},client_addr={0};
void * sock_write(void *p)
{
while(1)
{
char buf[1024] = {0};
printf("Please enter msg:");
gets(buf);
write(sock_client,buf,strlen(buf));//发送消息
if(strcmp(buf, "exit") == 0)
{
break;//退出循环
}
}
close(sock_client);
close(sock_service);
pthread_cancel(write_th);
pthread_cancel(read_th);
}
void * sock_read(void *p)
{
while(1)
{
char buf[1024] = {0};
read(sock_client, buf, sizeof(buf));//阻塞,,等待客户端发来消
if(strcmp(buf, "exit") == 0||strcmp(buf,"")==0)
{
break;//退出循环
}
printf("receive msg:%s\n", buf);//打印消息
}
close(sock_service);
close(sock_client);
pthread_cancel(write_th);
pthread_cancel(read_th);
}
void create_sock()
{
sock_service = socket(AF_INET,SOCK_STREAM,0);//创建套接字
service_addr.sin_family =AF_INET; //IPV4
service_addr.sin_port = htons(6666);//转大端字节序
service_addr.sin_addr.s_addr = INADDR_ANY;
bind(sock_service,(struct sockaddr *)&service_addr,sizeof(service_addr));
listen(sock_service,1);
int len =sizeof(client_addr);
sock_client = accept(sock_service,(struct sockaddr *)&client_addr,&len);
pthread_create(&write_th,NULL,sock_write,NULL);
pthread_create(&read_th,NULL,sock_read,NULL);
pthread_join(write_th,NULL);
pthread_join(read_th,NULL);
}
int main()
{
create_sock();
return 0;
}
评论