SOCKET编程实例.doc
Server.cpp/ Server.cpp : Defines the entry point for the console application./#include "stdafx.h"#include <iostream>#include <winsock.h>using namespace std;int main(int argc, char* argv) / 1.启动SOCKET库,版本为2.0WORD wVersionRequested;WSADATA wsaData;int err;wVersionRequested = MAKEWORD(2,0);err = WSAStartup( wVersionRequested, &wsaData );if ( err != 0 ) cout<<"Socket2.0初始化失败,Exit!"return -1;if ( LOBYTE( wsaData.wVersion ) != 2 |HIBYTE( wsaData.wVersion ) != 0 ) WSACleanup( );return -1; /2.创建TCP socket,SOCKET listenSocket = socket(AF_INET, /internetwork: UDP, TCP, etcSOCK_STREAM, /SOCK_STREAM说明是TCP socket0 /protocol);if (listenSocket = INVALID_SOCKET ) cout<<"Socket 创建失败,Exit!"return -1;/3.bind套接字,相当于给本地套接字赋值sockaddr_in myaddr; memset(&myaddr,0,sizeof(myaddr);myaddr.sin_family=AF_INET;myaddr.sin_addr.s_addr = inet_addr("127.0.0.1");myaddr.sin_port=htons(7861);if(bind(listenSocket,(sockaddr*)&myaddr,sizeof(myaddr)=SOCKET_ERROR)return -1;/5.listen 另一端的socketif (listen(listenSocket,5) = SOCKET_ERROR )elsecout<<"listen succeed!"<<endl;/6. accept 对方连接SOCKET clientSocket = accept(listenSocket,NULL,NULL);if (clientSocket = INVALID_SOCKET)cout<<"client socket error, exit!"<<endl;return -1;elsecout<<"accepted client socket!"<<endl;char buf1024;memset(buf,0,sizeof(buf);int len = recv(clientSocket,buf,1024,MSG_PEEK);if (len > 0)cout << "接收" << len <<"个字符:" <<buf << endl;if (!closesocket(listenSocket)WSAGetLastError();return -1;if (!closesocket(clientSocket) WSAGetLastError();return -1;if (!WSACleanup() WSAGetLastError();return -1;getchar();return 0;Client.cpp#include "stdafx.h"#include <iostream>#include <winsock.h>using namespace std;int main(int argc, char* argv) / 1.启动SOCKET库,版本为2.0WORD wVersionRequested;WSADATA wsaData;int err;wVersionRequested = MAKEWORD(2,0);err = WSAStartup( wVersionRequested, &wsaData );if ( err != 0 ) cout<<"Socket2.0初始化失败,Exit!"return -1;if ( LOBYTE( wsaData.wVersion ) != 2 |HIBYTE( wsaData.wVersion ) != 0 ) WSACleanup( );return -1; /2.创建TCP socket,SOCKET clientSocket = socket(AF_INET, /internetwork: UDP, TCP, etcSOCK_STREAM, /SOCK_STREAM说明是TCP socket0 /protocol);if (clientSocket = INVALID_SOCKET ) cout<<"Socket 创建失败,Exit!"return -1;/3.设置好服务器端的地址与端口号sockaddr_in servAddr; memset(&servAddr,0,sizeof(servAddr);servAddr.sin_family=AF_INET;servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");servAddr.sin_port=htons(7861); /像服务器发送链接请求if (connect(clientSocket,(sockaddr *)&servAddr,sizeof(servAddr) = SOCKET_ERROR)cout << "链接错误" << endl;elsecout << "服务器连接成功!" << endl;send(clientSocket,"中华人民共和国",20,MSG_DONTROUTE);getchar();closesocket(clientSocket);WSACleanup();return 0;