想用C语言想做一个类似mina 的框架,今天先到这里以后更新,目前刚调通
#include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <string.h> #include <netinet/in.h> #include <unistd.h> #include <stdlib.h> #include <arpa/inet.h> #define MAXN 4096 int main(void){ struct sockaddr_in A ,B ; char meg[MAXN]; char rev[MAXN]; socklen_t len; int s_socket,socket_conn; s_socket=socket(AF_INET,SOCK_STREAM,0); if(s_socket < 0){ printf("create socket failed\n"); return 1; } A.sin_family = AF_INET ; A.sin_port = htons(1234); A.sin_addr.s_addr = htonl(INADDR_ANY) ; bind(s_socket ,(struct sockaddr *)&A,sizeof(A)); listen(s_socket,5); printf("Server is Waiting ...\n"); len = sizeof(struct sockaddr_in) ; socket_conn = accept(s_socket,(struct sockaddr *)&B ,&len); if(socket_conn >= 0){ printf("get a connect\n"); while(1){ fgets(meg,MAXN,stdin); len = strlen(meg); if(meg[len-1] == '\n') meg[len-1] = 0 ; int ret=send(socket_conn,meg,strlen(meg)+1,0); if(ret==-1){ printf("send error\n"); break; } printf("send %d bytes\n",len); if(strcmp(meg,"quit") == 0){ printf("Server is cancelling the communication!\n"); break ; } recv(socket_conn,rev,MAXN,0); if(strcmp(rev,"quit")==0){ printf("Client is cancelling the communication!\n"); break ; } printf("receive %d bytes : %s\n",strlen(rev),rev); } close(socket_conn) ; } else{ printf("Faile to aceept!\n"); } close(s_socket); return 0; }