1、服务器代码serve.c
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
int acc_fd = -1;
//每个客户端服务器都会创建一个线程
void *serve_connect(void *arg)
{
int fd = acc_fd;
struct sockaddr_in addr=*(struct sockaddr_in*)arg;
char *buf = malloc(100);
while(1)
{
memset(buf,0,100);
//接收消息
int recv_ret = recv(fd,buf,100,0);
if(0==recv_ret)
{
printf("[端口号: %d,ip: %s]:已退出\n",ntohs(addr.sin_port),inet_ntoa(addr.sin_addr));
break;
}
printf("[端口号:%d,ip:%s] : %s\n",ntohs(addr.sin_port),inet_ntoa(addr.sin_addr),buf);
}
}
int main(int argc,char *argv[])//先传ip 再传端口
{
//1 创建套接字
int sock_ret = socket(AF_INET,SOCK_STREAM,0);
if(-1==sock_ret)
{
perror("creat sock fail");
return -1;
}
//2 绑定套接字与网络地址
struct sockaddr_in serve,cilent_addr;
serve.sin_family = AF_INET;
serve.sin_port = htons(atoi(argv[2]));
serve.sin_addr.s_addr = inet_addr(argv[1]);
int ret = bind(sock_ret,(struct sockaddr*)&serve,sizeof(serve));
if(-1==ret)
{
perror("bind fail");
}
//3 监听
int listen_ret = listen(sock_ret,4);
socklen_t cilent_len = sizeof(cilent_addr);
char *buf=malloc(100);
//创建线程
pthread_t tid;
while(1)
{
printf("等待连接\n");
acc_fd = accept(sock_ret,(struct sockaddr*)&cilent_addr,&cilent_len);//阻塞 等待连接
printf("连接的端口号为:%d.ip为: %s\n",ntohs(cilent_addr.sin_port),inet_ntoa(cilent_addr.sin_addr));
printf("连接成功\n");
pthread_create(&tid,NULL,serve_connect,(void*)&cilent_addr);
}
//关闭套接字
close(sock_ret);
close(acc_fd);
return 0;
}
2、客户端代码send.c
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
//1 创建套接字
int sock_ret = socket(AF_INET,SOCK_STREAM,0);
if(-1==sock_ret)
{
perror("creat sock fail");
return -1;
}
//2 绑定服务器地址
struct sockaddr_in serve;
serve.sin_family = AF_INET;
serve.sin_port = htons(atoi(argv[2]));
serve.sin_addr.s_addr = inet_addr(argv[1]);
int ret = bind(sock_ret,(struct sockaddr*)&serve,sizeof(serve));
if(-1==ret)
{
perror("bind fail");
}
//3 发起连接
char *buf = malloc(100);
int con_fd = connect(sock_ret,(const struct sockaddr*)&serve,sizeof(serve));
printf("连接成功\n");
while(1)
{
memset(buf,0,100);
fgets(buf,100,stdin);
//发送消息 send
ssize_t send_ret = send(sock_ret,buf,100,0);
if(-1==send_ret)
{
perror("send sock fail");
}
if(strcmp(buf,"ok\n")==0)
{
break;
}
}
//关闭套接字
close(sock_ret);
return 0;
}