赞
踩
服务端代码
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> int main() { int server_socket, client_socket; struct sockaddr_in server_addr, client_addr; char buffer[1024]; // 创建套接字 server_socket = socket(AF_INET, SOCK_STREAM, 0); // 初始化服务器地址结构体 memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(9999); // 绑定套接字到端口 bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)); // 监听连接请求 listen(server_socket, 5); printf("等待客户端连接...\n"); // 接受连接请求 socklen_t client_addr_len = sizeof(client_addr); client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len); printf("客户端 %s:%d 已连接\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); while (1) { // 接收客户端消息 memset(buffer, 0, sizeof(buffer)); recv(client_socket, buffer, sizeof(buffer), 0); printf("接收到客户端消息:%s\n", buffer); // 发送回复消息 memset(buffer, 0, sizeof(buffer)); printf("请输入回复消息:"); fgets(buffer, sizeof(buffer), stdin); send(client_socket, buffer, strlen(buffer), 0); // 判断是否退出 if (strcmp(buffer, "exit\n") == 0) { break; } } // 关闭套接字 close(client_socket); close(server_socket); return 0; }
客户端代码
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> int main() { int client_socket; struct sockaddr_in server_addr; char buffer[1024]; // 创建套接字 client_socket = socket(AF_INET, SOCK_STREAM, 0); // 初始化服务器地址结构体 memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); server_addr.sin_port = htons(9999); // 连接服务器 connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)); while (1) { // 发送消息 memset(buffer, 0, sizeof(buffer)); printf("请输入消息:"); fgets(buffer, sizeof(buffer), stdin); send(client_socket, buffer, strlen(buffer), 0); // 接收回复消息 memset(buffer, 0, sizeof(buffer)); recv(client_socket, buffer, sizeof(buffer), 0); printf("接收到回复消息:%s\n", buffer); // 判断是否退出 if (strcmp(buffer, "exit\n") == 0) { break; } } // 关闭套接字 close(client_socket); return 0; }
测试方法:
gcc -o server server.c
gcc -o client client.c
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。