服务器与客户端—— client

xiaoxiao2021-02-28  57

#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <strings.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #define SERV_PORT 9000 #define BUFF_SIZE 1024 struct user { int socketfd; char name[20]; char toName[20]; int result;   // 0 代表失败 1代表成功 2 代表别人给你发的信息 3代表没注册 4错误的指令 char msg[100]; int cmd;      // 5 代表注册用户  10 // 代表发送信息 }; void fillMsg(struct user *userInfo) { printf ("请输入要进行的操作: "); scanf ("%d", &userInfo->cmd); printf ("请输入你的用户名: "); scanf ("%s", userInfo->name); if (userInfo->cmd == 10) { printf ("请输入要发送的对象名称: "); scanf ("%s", userInfo->toName); printf ("请输入要发送的信息: "); scanf ("%s", userInfo->msg); } } void* write_to_server(void *arg) { int sfd = (int)arg; struct user userInfo; while (1) { memset(userInfo.msg, 0, sizeof(userInfo.msg)); fillMsg(&userInfo); int writeSize = write(sfd, &userInfo, sizeof(userInfo)); if (writeSize == -1) { perror("write"); return; } } } void* read_from_server(void *arg) { int sfd = (int)arg; struct user userInfo; while (1) { memset(userInfo.msg, 0, sizeof(userInfo.msg)); int readSize = read(sfd, &userInfo, sizeof(userInfo)); if (readSize == -1) { perror("read"); return; } switch(userInfo.result) { case 0: { printf ("\nsend error!\n"); break; } case 1: { printf ("\nsend success!\n"); break ; } case 2: { printf ("\n%s send msg to you: %s\n", userInfo.name, userInfo.msg); break; } case 3: { printf ("\nplease register first\n"); break; } case 4: { printf ("please input correct cmd\n"); break; } } } } int main(int argc, char *argv[]) { int server_sockfd; int ret; struct sockaddr_in client_addr;  if (argc != 2) { printf ("Usage:./client IP_ADDRESS\n"); return -1; } // 创建监听套接字 server_sockfd = socket(AF_INET, SOCK_STREAM, 0); if (server_sockfd == -1) { perror("create socket error"); return -1; } // 初始化服务器地址结构 bzero(&client_addr, sizeof(client_addr));     // 将地址结构变量清零 client_addr.sin_family = AF_INET;             // 选择IPV4地址 inet_aton(argv[1], &client_addr.sin_addr);    // 填写服务器地址 client_addr.sin_port = htons(SERV_PORT);      // 填写服务器端口 // 连接服务器 ret = connect(server_sockfd, (struct sockaddr *)&client_addr,  sizeof (client_addr)); if (ret != 0) { perror("connect error"); return -1; pthread_t tid1; pthread_t tid2; //  创建写线程 ret = pthread_create(&tid1, NULL, write_to_server, (void *)server_sockfd); if (ret != 0) { printf ("create pthread error!\n"); return -1; } // 创建读线程 ret = pthread_create(&tid2, NULL, read_from_server, (void *)server_sockfd); if (ret != 0) { printf ("create pthread error!\n"); return -1; } pthread_detach(tid1); // 线程分离 pthread_detach(tid2); // 线程分离 while (1); close(server_sockfd); return 0; }
转载请注明原文地址: https://www.6miu.com/read-29317.html

最新回复(0)