1.服务器代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
void send_message(void*sockfd)
{
int acc_fd = *((int *)sockfd);
char buf[100];
while(1) {
memset(buf, 0, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
int send_ret = send(acc_fd, buf, strlen(buf), 0);
if(send_ret == -1) {
perror("发送失败");
break;
}
}
}
int main(int argc, const char *argv[])
{
//1.创建套接字
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(-1==sockfd){
perror("创建套接字失败");
return -1;
}
//2.绑定IP+端口
//定义结构体
struct sockaddr_in server,cilent;
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
server.sin_addr.s_addr = inet_addr(argv[1]);
socklen_t server_len = sizeof(server);
socklen_t cilent_len = sizeof(cilent);
//绑定函数
bind(sockfd,(struct sockaddr *)&server,server_len);
//3.监听
listen(sockfd,5);
//4.等待连接
printf("等待连接...\n");
int acc_fd = accept(sockfd,(struct sockaddr*)&cilent,&cilent_len);
printf("连接成功...\n");
//5.创建子进程
pthread_t pid;
pthread_create(&pid, NULL, (void*)send_message, (void *)&acc_fd);
//6.通信
char*buf = malloc(100);
while(1){
memset(buf,0,100);
int recv_ret = recv(acc_fd,buf,100,0);
if(recv_ret <= 0) {
perror("接收失败或连接关闭");
break;
}
printf("[端口号: %d IP: %s]: %s",ntohs(cilent.sin_port),inet_ntoa(cilent.sin_addr),buf);
}
return 0;
}
2.客户端代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
// 接收消息的线程函数
void *receive_message(void *sockfd) {
int conn_fd = *((int *)sockfd);
char buf[100];
while(1) {
memset(buf, 0, sizeof(buf));
int recv_ret = recv(conn_fd, buf, sizeof(buf), 0);
if(recv_ret <= 0) {
perror("接收失败或连接关闭");
break;
}
printf("[服务器]: %s", buf);
}
return NULL;
}
int main(int argc, const char *argv[])
{
if(argc != 3) {
fprintf(stderr, "Usage: %s <IP> <Port>\n", argv[0]);
return -1;
}
// 1. 创建套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1){
perror("创建套接字失败");
return -1;
}
// 2. 设置服务器地址
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2])); // 使用 htons 转换端口
server.sin_addr.s_addr = inet_addr(argv[1]);
socklen_t server_len = sizeof(server);
// 3. 发起连接
int con_fd = connect(sockfd, (struct sockaddr*)&server, server_len);
if(con_fd == -1) {
perror("连接失败");
close(sockfd);
return -1;
}
printf("已连接到服务器...\n");
// 4. 创建子线程来接收消息
pthread_t recv_thread;
pthread_create(&recv_thread, NULL, receive_message, (void *)&sockfd);
// 主线程处理发送消息
char *buf = malloc(100);
while(1) {
memset(buf, 0, 100);
fgets(buf, 100, stdin);
int send_ret = send(sockfd, buf, strlen(buf), 0);
if(send_ret == -1) {
perror("发送失败");
break;
}
}
// 5. 清理资源
close(sockfd);
free(buf);
return 0;
}
3.运行效果