zoukankan      html  css  js  c++  java
  • 【网络】Windows 下 socket 编程范例

      1 #include "winsock2.h"
      2 #include <stdint.h>
      3 #include <stdio.h>
      4 
      5 #include <ctype.h>
      6 #include <time.h>
      7 
      8 #define MAX_BUF_LEN 1024
      9 
     10 #define ERR (-1)
     11 #define OK  0
     12 
     13 enum {
     14     TCP = 6,
     15     UDP = 17,
     16 };
     17 
     18 struct ClientPeer;
     19 typedef int (*ClientVoidHandler)(struct ClientPeer *);
     20 typedef int (*ClientRecvHandler)(struct ClientPeer *peer, char *buf, int len);
     21 typedef int (*ClientSendHandler)(struct ClientPeer *peer, const char *buf, int len);
     22 
     23 struct ClientPeerOp {
     24     ClientVoidHandler createsocket;
     25     ClientVoidHandler connect;
     26     ClientRecvHandler recv;
     27     ClientSendHandler send;
     28     ClientVoidHandler close;
     29 };
     30 
     31 struct ClientPeer {
     32     ClientPeerOp op;
     33 
     34     SOCKET fd;
     35 
     36     struct sockaddr_in remote;
     37 };
     38 
     39 int PeerEnvInit(void)
     40 {
     41     WORD sockVersion = MAKEWORD(2, 2);
     42     WSADATA wsaData;
     43     if (WSAStartup(sockVersion, &wsaData) != 0) {
     44         return ERR;
     45     }
     46     return OK;
     47 }
     48 
     49 int PeerEnvDestroy(void)
     50 {
     51     WSACleanup();
     52     return OK;
     53 }
     54 
     55 struct ClientPeer *ClientPeerNewWithRemote(const char *ip, unsigned short port)
     56 {
     57     struct ClientPeer *peer = (struct ClientPeer *)calloc(1, sizeof(struct ClientPeer));
     58 
     59     peer->remote.sin_family = AF_INET;
     60     peer->remote.sin_port = htons(port);
     61     peer->remote.sin_addr.S_un.S_addr = inet_addr(ip);
     62 
     63     return peer;
     64 };
     65 
     66 int TCPClientPeerCreateSocket(struct ClientPeer *peer)
     67 {
     68     SOCKET fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
     69     if (fd == INVALID_SOCKET) {
     70         printf("socket error !");
     71         return ERR;
     72     }
     73     peer->fd = fd;
     74     return OK;
     75 }
     76 
     77 int TCPClientPeerConnect(struct ClientPeer *peer)
     78 {
     79     if (connect(peer->fd, (struct sockaddr *)&(peer->remote), sizeof(struct sockaddr)) == SOCKET_ERROR) {
     80         printf("connect error !");
     81         return ERR;
     82     }
     83     return OK;
     84 }
     85 
     86 int TCPClientPeerSend(struct ClientPeer *peer, const char *buf, int len)
     87 {
     88     return send(peer->fd, buf, len, 0);
     89 }
     90 
     91 int TCPClientPeerRecv(struct ClientPeer *peer, char *buf, int len)
     92 {
     93     return recv(peer->fd, buf, len, 0);
     94 }
     95 
     96 int TCPClientPeerClose(struct ClientPeer *peer)
     97 {
     98     closesocket(peer->fd);
     99     return OK;
    100 }
    101 
    102 
    103 int UDPClientPeerCreateSocket(struct ClientPeer *peer)
    104 {
    105     SOCKET fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    106     if (fd == INVALID_SOCKET) {
    107         printf("socket error !");
    108         return ERR;
    109     }
    110     peer->fd = fd;
    111     return OK;
    112 }
    113 
    114 int UDPClientPeerConnect(struct ClientPeer *peer)
    115 {
    116     return OK;
    117 }
    118 
    119 int UDPClientPeerSend(struct ClientPeer *peer, const char *buf, int len)
    120 {
    121     return sendto(peer->fd, buf, len, 0, (struct sockaddr *)&(peer->remote), sizeof(struct sockaddr));
    122 }
    123 
    124 int UDPClientPeerRecv(struct ClientPeer *peer, char *buf, int len)
    125 {
    126     int addrlen = sizeof(struct sockaddr_in);
    127     return recvfrom(peer->fd, buf, len, 0, (struct sockaddr *)&(peer->remote), &addrlen);
    128 }
    129 
    130 int UDPClientPeerClose(struct ClientPeer *peer)
    131 {
    132     closesocket(peer->fd);
    133     return OK;
    134 }
    135 
    136 struct ClientPeer *ClientPeerFactory(int type, const char *ip, unsigned short port)
    137 {
    138     struct ClientPeer *peer = ClientPeerNewWithRemote(ip, port);
    139 
    140     switch (type) {
    141         case TCP:
    142             peer->op.createsocket = TCPClientPeerCreateSocket;
    143             peer->op.connect = TCPClientPeerConnect;
    144             peer->op.recv = TCPClientPeerRecv;
    145             peer->op.send = TCPClientPeerSend;
    146             peer->op.close = TCPClientPeerClose;
    147             break;
    148 
    149         case UDP:
    150             peer->op.createsocket = UDPClientPeerCreateSocket;
    151             peer->op.connect = UDPClientPeerConnect;
    152             peer->op.recv = UDPClientPeerRecv;
    153             peer->op.send = UDPClientPeerSend;
    154             peer->op.close = UDPClientPeerClose;
    155             break;
    156     }
    157 
    158     return peer;
    159 }
    160 
    161 
    162 
    163 
    164 struct ServerPeer;
    165 typedef int (*ServerVoidHandler)(struct ServerPeer *);
    166 typedef int (*ServerRecvHandler)(struct ServerPeer *peer, char *buf, int len);
    167 typedef int (*ServerSendHandler)(struct ServerPeer *peer, const char *buf, int len);
    168 
    169 struct ServerPeerOp {
    170     ServerVoidHandler createsocket;
    171     ServerVoidHandler bindaddr;
    172     ServerVoidHandler listen;
    173     ServerVoidHandler accept;
    174     ServerRecvHandler recv;
    175     ServerSendHandler send;
    176     ServerVoidHandler closeclient;
    177     ServerVoidHandler close;
    178 };
    179 
    180 struct ServerPeer {
    181     SOCKET lfd;
    182     SOCKET rfd;
    183 
    184     struct sockaddr_in laddr;
    185     struct sockaddr_in raddr;
    186 
    187     struct ServerPeerOp op;
    188 };
    189 
    190 
    191 struct ServerPeer *ServerPeerNewWithAddr(const char *ip, unsigned short port)
    192 {
    193     struct ServerPeer *peer = (struct ServerPeer *)calloc(1, sizeof(struct ServerPeer));
    194 
    195     peer->laddr.sin_family = AF_INET;
    196     peer->laddr.sin_port = htons(port);
    197     peer->laddr.sin_addr.S_un.S_addr = inet_addr(ip);
    198 
    199     return peer;
    200 }
    201 
    202 int TCPServerPeerCreateSocket(struct ServerPeer *peer)
    203 {
    204 
    205     SOCKET fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    206     if (fd == INVALID_SOCKET) {
    207         printf("socket error !");
    208         return ERR;
    209     }
    210     peer->lfd = fd;
    211     return OK;
    212 }
    213 
    214 int TCPServerPeerBindaddr(struct ServerPeer *peer)
    215 {
    216     if (bind(peer->lfd, (struct sockaddr *)&(peer->laddr), sizeof(struct sockaddr)) == SOCKET_ERROR) {
    217         printf("bind error !");
    218         return ERR;
    219     }
    220 
    221     return OK;
    222 }
    223 
    224 int TCPServerPeerListen(struct ServerPeer *peer)
    225 {
    226     if (listen(peer->lfd, 5) == SOCKET_ERROR) {
    227         printf("listen error !");
    228         return ERR;
    229     }
    230 
    231     return OK;
    232 }
    233 
    234 int TCPServerPeerAccept(struct ServerPeer *peer)
    235 {
    236     int len = sizeof(struct sockaddr_in);
    237     peer->rfd = accept(peer->lfd, (struct sockaddr *)&(peer->raddr), &len);
    238     if (peer->rfd == INVALID_SOCKET) {
    239         printf("accept error !");
    240         return ERR;
    241     }
    242     return OK;
    243 }
    244 
    245 int TCPServerPeerSend(struct ServerPeer *peer, const char *buf, int len)
    246 {
    247     return send(peer->rfd, buf, len, 0);
    248 }
    249 
    250 int TCPServerPeerRecv(struct ServerPeer *peer, char *buf, int len)
    251 {
    252     return recv(peer->rfd, buf, len, 0);
    253 }
    254 
    255 int TCPServerPeerCloseClient(struct ServerPeer *peer)
    256 {
    257     closesocket(peer->rfd);
    258     return OK;
    259 }
    260 
    261 int TCPServerPeerClose(struct ServerPeer *peer)
    262 {
    263     closesocket(peer->lfd);
    264     return OK;
    265 }
    266 
    267 
    268 
    269 
    270 
    271 
    272 
    273 
    274 int UDPServerPeerCreateSocket(struct ServerPeer *peer)
    275 {
    276 
    277     SOCKET fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    278     if (fd == INVALID_SOCKET) {
    279         printf("socket error !");
    280         return ERR;
    281     }
    282     peer->lfd = fd;
    283     return OK;
    284 }
    285 
    286 int UDPServerPeerBindaddr(struct ServerPeer *peer)
    287 {
    288     if (bind(peer->lfd, (struct sockaddr *)&(peer->laddr), sizeof(struct sockaddr)) == SOCKET_ERROR) {
    289         printf("bind error !");
    290         return ERR;
    291     }
    292 
    293     return OK;
    294 }
    295 
    296 int UDPServerPeerListen(struct ServerPeer *peer)
    297 {
    298     return OK;
    299 }
    300 
    301 int UDPServerPeerAccept(struct ServerPeer *peer)
    302 {
    303     return OK;
    304 }
    305 
    306 int UDPServerPeerSend(struct ServerPeer *peer, const char *buf, int len)
    307 {
    308     return sendto(peer->lfd, buf, len, 0, (struct sockaddr *)&(peer->raddr), sizeof(struct sockaddr_in));
    309 }
    310 
    311 int UDPServerPeerRecv(struct ServerPeer *peer, char *buf, int len)
    312 {
    313     int addrlen = sizeof(struct sockaddr_in);
    314     return recvfrom(peer->lfd, buf, len, 0, (struct sockaddr *)&(peer->raddr), &addrlen);
    315 }
    316 
    317 int UDPServerPeerCloseClient(struct ServerPeer *peer)
    318 {
    319     return OK;
    320 }
    321 
    322 int UDPServerPeerClose(struct ServerPeer *peer)
    323 {
    324     closesocket(peer->lfd);
    325     return OK;
    326 }
    327 
    328 
    329 struct ServerPeer *ServerPeerFactory(int type, const char *ip, unsigned short port)
    330 {
    331     struct ServerPeer *peer = ServerPeerNewWithAddr(ip, port);
    332 
    333     switch (type) {
    334         case TCP:
    335             peer->op.createsocket = TCPServerPeerCreateSocket;
    336             peer->op.bindaddr = TCPServerPeerBindaddr;
    337             peer->op.listen = TCPServerPeerListen;
    338             peer->op.accept = TCPServerPeerAccept;
    339             peer->op.recv = TCPServerPeerRecv;
    340             peer->op.send = TCPServerPeerSend;
    341             peer->op.closeclient = TCPServerPeerCloseClient;
    342             peer->op.close = TCPServerPeerClose;
    343             break;
    344 
    345         case UDP:
    346             peer->op.createsocket = UDPServerPeerCreateSocket;
    347             peer->op.bindaddr = UDPServerPeerBindaddr;
    348             peer->op.listen = UDPServerPeerListen;
    349             peer->op.accept = UDPServerPeerAccept;
    350             peer->op.recv = UDPServerPeerRecv;
    351             peer->op.send = UDPServerPeerSend;
    352             peer->op.closeclient = UDPServerPeerCloseClient;
    353             peer->op.close = UDPServerPeerClose;
    354             break;
    355     }
    356 
    357     return peer;
    358 }
    359 
    360 
    361 struct Peer;
    362 typedef void (*runhandler)(struct Peer *);
    363 
    364 
    365 
    366 struct Peer {
    367     union {
    368         ClientPeer *client;
    369         ServerPeer *server;
    370     };
    371     runhandler op;
    372 };
    373 
    374 void ServerRun(struct Peer *p)
    375 {
    376     struct ServerPeer *peer = p->server;
    377     struct ServerPeerOp *op = &(peer->op);
    378 
    379     op->createsocket(peer);
    380     op->bindaddr(peer);
    381     op->listen(peer);
    382     op->accept(peer);
    383     while (1) {
    384         int ret;
    385         char buf[MAX_BUF_LEN];
    386         time_t t = time(NULL);
    387 
    388         memset(buf, 0, sizeof(buf));
    389         op->recv(peer, buf, sizeof(buf));
    390 
    391         printf("server recv: %s
    ", buf);
    392 
    393         strncpy(buf, ctime(&t), sizeof(buf));
    394         ret = op->send(peer, buf, strlen(buf));
    395         if (ret <= 0) {
    396             printf("send failed(%d - %d).
    ", ret, WSAGetLastError());
    397             break;
    398         }
    399     }
    400 }
    401 
    402 void ClientRun(struct Peer *p)
    403 {
    404     struct ClientPeer *peer = p->client;
    405     struct ClientPeerOp *op = &(peer->op);
    406 
    407     op->createsocket(peer);
    408     op->connect(peer);
    409 
    410     char hello[] = "Hello, I am client.
    ";
    411 
    412     op->send(peer, hello, strlen(hello));
    413 
    414     while (1) {
    415         char buf[MAX_BUF_LEN] = {0};
    416         int len = 0;
    417 
    418         len = op->recv(peer, buf, sizeof(buf));
    419         if (len <= 0) {
    420             printf("recv error (%d - %d) !
    ", len, WSAGetLastError());
    421             break;
    422         }
    423         printf("client recv: %s
    ", buf);
    424 
    425         for (int i = 0; i < len; i++) {
    426             buf[i] = toupper(buf[i]);
    427         }
    428         op->send(peer, buf, strlen(buf));
    429 
    430         Sleep(1000);
    431     }
    432 
    433     op->close(peer);
    434 }
    435 
    436 
    437 enum {
    438     TCP_SERVER = 1,
    439     TCP_CLIENT,
    440     UDP_SERVER,
    441     UDP_CLIENT,
    442 };
    443 
    444 struct Peer *PeerFactory(int type, const char *ip, unsigned short port)
    445 {
    446     struct Peer *peer = (struct Peer *)calloc(1, sizeof(struct Peer));
    447 
    448     switch (type) {
    449         case TCP_SERVER:
    450             peer->server = ServerPeerFactory(TCP, ip, port);
    451             peer->op = ServerRun;
    452             break;
    453         case TCP_CLIENT:
    454             peer->client = ClientPeerFactory(TCP, ip, port);
    455             peer->op = ClientRun;
    456             break;
    457         case UDP_SERVER:
    458             peer->server = ServerPeerFactory(UDP, ip, port);
    459             peer->op = ServerRun;
    460             break;
    461         case UDP_CLIENT:
    462             peer->client = ClientPeerFactory(UDP, ip, port);
    463             peer->op = ClientRun;
    464             break;
    465     }
    466 
    467     return peer;
    468 };
    469 
    470 
    471 void PeerRun(struct Peer *peer)
    472 {
    473     peer->op(peer);
    474 }
    475 
    476 
    477 int main()
    478 {
    479     int type;
    480     printf("input way:              
    
    481               1. tcp server         
    
    482               2. tcp client         
    
    483               3. udp server         
    
    484               4. udp client         
    
    485            ");
    486     scanf("%d", &type);
    487 
    488     const char *ip = "127.0.0.1";
    489     unsigned short port = 10240;
    490 
    491     PeerEnvInit();
    492 
    493     struct Peer *peer = NULL;
    494 
    495     switch(type) {
    496         case 1:
    497         case 2:
    498         case 3:
    499         case 4:
    500             peer = PeerFactory(type, ip, port);
    501             PeerRun(peer);
    502             break;
    503         default:
    504             printf("unknown.");
    505             break;
    506     }
    507 
    508     PeerEnvDestroy();
    509 }

    使用的是 codeblock,需要链接 wsock32

  • 相关阅读:
    3.5——课题选择
    3.8——K-th Substring
    01背包dp
    贪心——IQ
    Secret Project Gym
    快速幂&矩阵快速幂
    用栈非递归实现fib数列
    CodeForces Round #590 (Div 3)
    SQL Server常见问题
    SQL基础函数
  • 原文地址:https://www.cnblogs.com/YBhello/p/11372917.html
Copyright © 2011-2022 走看看