1、sockets(套接字)编程有三种,流式套接字(SOCK_STREAM ),数据报套接字(SOCK_DGRAM),原始套接字(SOCK_RAW);基于 TCP 的 socket 编程是采用的流式套接字。服务器端编程的步骤:1:加载套接字库,创建套接字(WSAStartup()/socket();2:绑定套接字到一个 IP 地址和一个端口上(bind();3:将套接字设置为监听模式等待连接请求(listen() ;4:请求到来后,接受连接请求,返回一个新的对应于此次连接的套接字(accept() ;5:用返回的套接字和客户端进行通信(send()/recv();6:返回,等待另一连接请求;7:关
2、闭套接字,关闭加载的套接字库(closesocket()/WSACleanup()。客户端编程的步骤:1:加载套接字库,创建套接字(WSAStartup()/socket();2:向服务器发出连接请求(connect();3:和服务器端进行通信(send()/recv() ;4:关闭套接字,关闭加载的套接字库(closesocket()/WSACleanup()。第一式: 加载/ 释放 Winsock 库:1.加载方法:WSADATA wsa;/*初始化 socket 资源*/if (WSAStartup(MAKEWORD(1,1), /代表失败2.释放方法:WSACleanup();第二式:
3、 构造 SOCKET:1.服务端:构造监听 SOCKET,流式 SOCKET.SOCKET Listen_Sock = socket(AF_INET, SOCK_STREAM, 0)2.客户端:构造通讯 SOCKET,流式 SOCKET.SOCKET Client_Sock = socket(AF_INET, SOCK_STREAM, 0)第三式:配置监听地址和端口:1.服务端: SOCKADDR_IN serverAddrZeroMemory(char *)serverAddr.sin_family = AF_INET;serverAddr.sin_port = htons(1234); /
4、*本地监听端口 :1234*/serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); /*有 IP*/第四式: 绑定 SOCKET:1.服务端:绑定监听 SOCKET.bind(Listen_Sock,(struct sockaddr *) WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 1, 1 ); err = WSAStartup( wVersionRequested, if ( err != 0 ) return; if ( LOBYTE( wsaData.wVersion ) !=
5、 1 | HIBYTE( wsaData.wVersion ) != 1 ) WSACleanup( ); return; SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY); addrSrv.sin_family=AF_INET; addrSrv.sin_port=htons(6000); bind(sockSrv,(SOCKADDR*) listen(sockSrv,5); SOCKADDR_IN addrClien
6、t; int len=sizeof(SOCKADDR); while(1) SOCKET sockConn=accept(sockSrv,(SOCKADDR*) char sendBuf50; sprintf(sendBuf,“Welcome %s to here!“,inet_ntoa(addrClient.sin_addr); send(sockConn,sendBuf,strlen(sendBuf)+1,0); char recvBuf50; recv(sockConn,recvBuf,50,0); printf(“%sn“,recvBuf); closesocket(sockConn)
7、; #include #include void main()WORD wVersionRequested;WSADATA wsaData;int err;wVersionRequested = MAKEWORD( 1, 1 );err = WSAStartup( wVersionRequested, if ( err != 0 ) return;if ( LOBYTE( wsaData.wVersion ) != 1 |HIBYTE( wsaData.wVersion ) != 1 ) WSACleanup( );return;SOCKET sockClient=socket(AF_INET
8、,SOCK_STREAM,0);SOCKADDR_IN addrSrv;addrSrv.sin_addr.S_un.S_addr=inet_addr(“127.0.0.1“);addrSrv.sin_family=AF_INET;addrSrv.sin_port=htons(6000);connect(sockClient,(SOCKADDR*)send(sockClient,“hello“,strlen(“hello“)+1,0);char recvBuf50;recv(sockClient,recvBuf,50,0);printf(“%sn“,recvBuf);closesocket(sockClient);WSACleanup();