1.client端(读)
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> void error_handling(char *msg); int main(int argc, char *argv[]) { int sock_fd; struct sockaddr_in serv_addr; char message[30] = {0}; int rcv_len; if (argc != 3) { printf("Usage: %s <IP> <port>\n", argv[0]); exit(1); } sock_fd = socket(AF_INET, SOCK_STREAM, 0); if (sock_fd == -1) error_handling("sock() error"); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr(argv[1]);// server‘s IP addr serv_addr.sin_port = htons(atoi(argv[2]));//port if (connect(sock_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1) error_handling("connect() error!"); rcv_len = read(sock_fd, message, sizeof(message) - 1); if (rcv_len == -1) error_handling("read() error!"); printf("Message from server: %s\n", message); printf("read length : %d\n",rcv_len); close(sock_fd); return 0; } void error_handling(char *message) { fputs(message, stderr); fputc(‘\n‘, stderr); exit(1); }
如果是在client中发送数据,只需将read修改为write即可。
2.server(发送)
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> void error_handling(char *msg); int main(int argc, char *argv[]) { int serv_sock_fd; int clnt_sock_fd; struct sockaddr_in serv_addr; struct sockaddr_in clnt_addr; socklen_t clnt_addr_size; char message[] = "This is a sample TCP?sserver!"; if (argc != 2) { printf("Usage: %s <port>\n", argv[0]); exit(1); } serv_sock_fd = socket(AF_INET, SOCK_STREAM, 0); if (serv_sock_fd == -1) error_handling("sock() error"); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(atoi(argv[1])); if (bind(serv_sock_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1) error_handling("bind() error"); if (listen(serv_sock_fd, 5) == -1) error_handling("listen() error"); clnt_addr_size = sizeof(clnt_addr); clnt_sock_fd = accept(serv_sock_fd, (struct sockaddr*)&clnt_addr, &clnt_addr_size); if (clnt_sock_fd == -1) error_handling("accept() error"); write(clnt_sock_fd, message, sizeof(message)); close(clnt_sock_fd); close(serv_sock_fd); return 0; } void error_handling(char *message) { fputs(message, stderr); fputc(‘\n‘, stderr); exit(1); }
如果是在server端接收数据,只需将write修改为read即可。
3,以上,在Linux下分别gcc编译,先运行server程序,然后运行client程序,server端等待client的连接,一旦连接并完成数据发送,server关闭。
4,示例程序的server只能连接一个client端,并且未进行数据收发的正确性验证。
时间: 2024-10-16 19:13:24