//client
#include <iostream> #include <WinSock2.h> #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib using namespace std; int main() { SOCKET so; WSADATA ws; if (WSAStartup(MAKEWORD(2, 2), &ws) != 0) { cout << "WSAStartup failed" << endl; } if((so = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { cout << "socket failed" << endl; } //绑定地址时需要将主机字节序转换成网络字节序,这个地址是需要连接的ip和端口 sockaddr_in addr = {0}; addr.sin_addr.s_addr = inet_addr("127.0.0.1");//此地址是网络字节序,需要将主机字节序抓换成网络字节序,inet_addr:可以转换ip地址 addr.sin_family = AF_INET; addr.sin_port = htons(2000); //addr.sin_zero if(connect(so, (sockaddr*)&addr, sizeof(sockaddr)) == SOCKET_ERROR)//connect,系统自动分配端口号和IP,无需自己绑定 { cout << "connect failed" << endl; } char sendBuf[4096]; while(1) { fgets(sendBuf, 4096, stdin); if(send(so, sendBuf, strlen(sendBuf), 0) < 0)//send { cout << "send failed" << endl; } } system("pause"); closesocket(so); WSACleanup(); return 0; }
//server
#include <iostream> #include <winsock2.h> #include <windows.h> #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib using namespace std; int main() { //有一种非阻塞的socket,没有用过 SOCKET so; WSADATA ws; if (WSAStartup(MAKEWORD(2, 2), &ws) != 0) { cout << "WSAStartup failed" << endl; } if((so = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)//创建socket { cout << "scoket failed" << endl; } sockaddr_in addr = {0}; addr.sin_addr.s_addr = inet_addr("127.0.0.1");//将字符串ip地址转换成网络字节顺序的整型值 addr.sin_family = AF_INET; addr.sin_port = htons(2000);//此地址是网络字节序,需要将主机字节序抓换成网络字节序 //addr.sin_zero if(bind(so, (struct sockaddr*)&addr, sizeof(sockaddr)) != 0)//bind { cout << "bind failed" << endl; } if(listen(so, 10) == -1)//监听so套接字 { cout << "listen failed" << endl; } sockaddr_in addrclient; int client; int nrecv; char buff[4096]; while (true) { if((client = accept(so, (struct sockaddr*)&addrclient, NULL)) == -1)//accept客户端的连接,返回连接的套接字,此函数时阻塞函数 { continue; } //输出IP //cout << inet_ntoa(addrclient.sin_addr.s_addr);//将网络格式的ip转换成.分格式的字符串 while (true) { nrecv = recv(client, buff, 4096, 0);//recv也是阻塞函数 buff[nrecv] = ‘\0‘; cout << buff << endl; } } WSACleanup(); system("pause"); return 0; }
有点小bug
原文:http://www.cnblogs.com/zzyoucan/p/3804329.html