服务器端:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
struct TCP_data{
struct sockaddr_in tcp;
int id;
};
void* serve_listened(void* c){
struct TCP_data *client = c;
char buf[100] = {0};
while(strcmp(buf,"end\n")!=0){
//接收消息
int jump = recv(client->id,buf,100,0);
if(jump!=0&&jump!=-1)
printf("客户端IP为:%s\n端口号为:%d\n数据为:%s\n",inet_ntoa(client->tcp.sin_addr),ntohs(client->tcp.sin_port),buf);
else
break;
memset(buf,0,100);
}
printf("已退出!\n");
return NULL;
}
int main(int argc, char *argv[]){
if(argc!=3){
printf("传参有误!\n");
return 0;
}
//创建套接字
int sock_fd = socket(AF_INET,SOCK_STREAM,0);
if(-1 == sock_fd){
perror("创建套接字失败!\n");
return -1;
}
//绑定服务器
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_fd, (struct sockaddr *)&serve, sizeof(serve));
if(ret == -1){
perror("绑定失败!\n");
}
int listen_ret = listen(sock_fd,4);
if(listen_ret == -1){
perror("监听模式设置失败!\n");
}
struct sockaddr_in *client = calloc(4,sizeof(struct sockaddr_in));
int i=0,j=0;
socklen_t size=sizeof(struct sockaddr_in);
pthread_t tid[4];
//等待连接
while(1){
struct TCP_data data;
data.id = accept(sock_fd,(struct sockaddr*)(client+i),&size);
data.tcp = *(client+i);
printf("客户端IP为:%s\n端口号为:%hu\n",inet_ntoa(data.tcp.sin_addr),data.tcp.sin_port);
if(data.id!=-1)i++;
if(i!=j){
if(pthread_create(tid+j,NULL,serve_listened,(void*)&data)){
printf("线程创建失败!\n");
return -1;
}
j=i;
}
}
close(sock_fd);
return 0;
}
客户端:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc!=3){
printf("传参有误!\n");
return 0;
}
//创建套接字
int sock_fd = socket(AF_INET,SOCK_STREAM,0);
if(-1 == sock_fd){
perror("创建套接字失败!\n");
return -1;
}
//绑定服务器
struct sockaddr_in client;
client.sin_family = AF_INET;
client.sin_port = htons(atoi(argv[2]));
client.sin_addr.s_addr = inet_addr(argv[1]);
//链接
int con = connect(sock_fd,(struct sockaddr*)&client,sizeof(client));
if(-1 == con){
printf("连接失败!\n");
}
char *buf = calloc(1,100);
//畅聊
while(strcmp(buf,"end\n")){
//接收消息
fgets(buf,100,stdin);
send(sock_fd, buf, 100, MSG_NOSIGNAL);
printf("发送为:%s\n",buf);
memset(buf,0,100);
}
close(sock_fd);
return 0;
}