【网络】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\n", 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).\n", 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.\n";
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) !\n", len, WSAGetLastError());
421             break;
422         }
423         printf("client recv: %s\n", 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:              \n\
481               1. tcp server         \n482               2. tcp client         \n483               3. udp server         \n484               4. udp client         \n485            ");
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

原文地址:https://www.cnblogs.com/YBhello/p/11372917.html

时间: 2024-11-08 22:34:47

【网络】Windows 下 socket 编程范例的相关文章

windows下socket编程小例子

服务端 首先引进头文件winsock2.h和库文件ws2_32.lib(开发环境为vs2015) 加载套接字库和创建套接字 绑定套接字到一个IP地址和端口上 监听客户端发来的连接请求 接收或发送信息 关闭套接字,套接字库 客户端 首先引进头文件winsock2.h和库文件ws2_32.lib(开发环境为vs2015) 加载套接字库,创建套接字对象 向服务端发出连接请求 收发信息 关闭套接字和套接字库 注释 WSAStartup结构体中主要包含了系统所支持的Winsock版本信息 WSAstart

windows下socket编程实现client和server双向通信

服务端代码server.c // server.cpp : Defines the entry point for the console application. // #include <stdio.h> #include <Winsock2.h> //Socket的函数调用 #include <windows.h> #define BUF_SIZE 6400 // 缓冲区大小 #pragma comment (lib, "ws2_32") //

Linux下Socket编程

http://blog.chinaunix.net/uid-20733992-id-3450058.html 原文地址:Linux下Socket编程 作者:yulianliu1218 Linux下Socket编程 什么是Socket Socket接口是TCP/IP网络的API,Socket接口定义了许多函数或例程,程序员可以用它们来开发TCP/IP网络上的应用程序.要学Internet上的TCP/IP网络编程,必须理解Socket接口. Socket接口设计者最先是将接口放在Unix操作系统里面

Linux下Socket编程的端口问题( Bind error: Address already in use )

Linux下Socket编程的端口问题( Bind error: Address already in use ) 在进行linux网络编程时,每次修改了源代码并再次编译运行时,常遇到下面的地使用错误: Bind error: Address already in use 虽然用Ctrl+C强制结束了进程,但错误依然存在,用netstat -an |grep 5120和ps aux |grep 5120都还能看到刚才用Ctrl+C“强制结束”了的进程,端口还是使用中,只好每次用kill结束进程,

Linux下socket编程,附带tcp例子

1.网络中进程之间如何通信? 本地的进程间通信(IPC)有很多种方式,但可以总结为下面4类: 消息传递(管道.FIFO.消息队列) 同步(互斥量.条件变量.读写锁.文件和写记录锁.信号量) 共享内存(匿名的和具名的) 远程过程调用(Solaris门和Sun RPC) 但这些都不是本文的主题!我们要讨论的是网络中进程之间如何通信?首要解决的问题是如何唯一标识一个进程,否则通信无从谈起!在本地可以通过进程PID来唯一标识一个进程,但是在网络中这是行不通的.其实TCP/IP协议族已经帮我们解决了这个问

Linux下socket编程基本知识

本文档主要讲解了Linux下socket编程的一些基本知识,主要包括套接字和字节序的概念,以及一些常用的结构体和函数. 本文是在网易云课堂学习过程中的记录,这个老师讲得很不错,推荐大家围观. Linux网络编程 Linux网络编程|人工智能物联网 1.概念 1.1套接字(socket) Socket(套接字)是一种通讯机制,它包含一整套的调用接口和数据结构的定义,它给应用进程提供了使用如TCP/UDP等网络协议进行网络通讯的手段. Linux中的网络编程通过socket接口实现,socket既是

初探WINDOWS下IME编程

初探WINDOWS下IME编程作者:广东南海市昭信科技有限公司-李建国 大家知道,DELPHI许多控件有IME属性.这么好用的东西VC可没自带,怎么办呢?其实,可通过注册表,用API实现.下面说一下本人对IME的研究结果,并提供示例工程供大家参考: 下载示例工程 10.6K 本文示例程序运行结果如上图1.将用到的API RegOpenKey:打开注册表一键RegQueryValue:查询一键值RegQueryValueEx:同上RegCloseKey:关闭打开的键 LoadKeyboardLay

在VMware中为CentOS配置静态ip并可访问网络-Windows下的VMware

在VMware中为CentOS配置静态ip并可访问网络-Windows下的VMware 首先确保虚拟网卡(VMware Network Adapter VMnet8)是开启的,然后在windows的命令行里输入“ipconfig /all”,找到VMware Network Adapter VMnet8的ipv4地址(例如:192.168.16.1),如下图: 然后确保虚拟机centos的网络配置是NAT,如下图: 最后按照以下方法设置静态ip: 启动并进入centos系统,在终端中输入“vim

c++ 网络编程(四)TCP/IP LINUX/windows下 socket 基于I/O复用的服务器端代码 解决多进程服务端创建进程资源浪费问题

原文作者:aircraft 原文链接:https://www.cnblogs.com/DOMLX/p/9613861.html 好了,继上一篇说到多进程服务端也是有缺点的,每创建一个进程就代表大量的运算与内存空间占用,相互进程数据交换也很麻烦. 本章的I/O模型就是可以解决这个问题的其中一种模型...废话不多说进入主题-- I/O复用技术主要就是select函数的使用. 一.I/O复用预备知识--select()函数用法与作用 select()用来确定一个或多个套接字的状态(更为本质一点来讲是文