socket tcp 服务端 ,客户端
tcp_server.cpp
#include <WinSock2.h> #include <iostream> using namespace std; //指定动态库的lib文件 #pragma comment(lib,"ws2_32.lib") int main() { //初始化winsock2.2 相关的动态库 WSADATA wd; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) { //0表示成功 cout << "WSAStartup error:" << WSAGetLastError() << endl; return 0; } //1,创建tcp socket 流式套接字 SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s == INVALID_SOCKET) { cout << "socket error:" << WSAGetLastError() << endl; return 0; } //2,绑定socket 到一个 ip地址和端口 sockaddr_in addr; //网络字节序 addr.sin_port = htons(8000); addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addr.sin_family = AF_INET; //地址族 int len = sizeof(sockaddr_in); if (bind(s, (sockaddr*)&addr, len) == SOCKET_ERROR) { cout << "bind error:" << WSAGetLastError() << endl; return 0; } //3,监听 //5代表正在等待完成相应的tcp三次握手过程的队列长度 if (listen(s, 5) == SOCKET_ERROR) { cout << "listen error:" << WSAGetLastError() << endl; return 0; } //4,接受客户端请求,并且返回和客户端通讯的套接字 sockaddr_in addrClient; memset(&addrClient, 0, sizeof(sockaddr_in)); len = sizeof(sockaddr_in); SOCKET c = accept(s, (sockaddr*)&addrClient, &len); //成功返回套接字 if (c == INVALID_SOCKET) { cout << "accept error:" << WSAGetLastError() << endl; return 0; } //5,发送,接受消息 int ret = 0; do { //向客户端发送数据, 用accept 返回的套接字c ret = send(c, "i am server!", strlen("i am server!"), 0); //接收客户端的消息 char buf[64] = { '\0' }; //把flag 置为0 ret = recv(c, buf, 64, 0); cout << "recv:"<<inet_ntoa(addrClient.sin_addr) <<": " << buf << endl; } while (ret != SOCKET_ERROR && ret != 0); //对方关闭返回0, 错误是error //6 关闭 closesocket(s); //清理winsock环境 WSACleanup(); //netstat -ao return 0; }
tcp_client.cpp
#include <WinSock2.h> #include <iostream> using namespace std; //指定动态库的lib文件 #pragma comment(lib,"ws2_32.lib") int main() { //初始化winsock2.2 相关的动态库 WSADATA wd; if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) { //0表示成功 cout << "WSAStartup error:" << WSAGetLastError() << endl; return 0; } //1,创建tcp socket 流式套接字 SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s == INVALID_SOCKET) { cout << "socket error:" << WSAGetLastError() << endl; return 0; } //2,链接服务端 sockaddr_in addr; //网络字节序 addr.sin_port = htons(8000); addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addr.sin_family = AF_INET; //地址族 int len = sizeof(sockaddr_in); if (connect(s, (sockaddr*)&addr, len) == SOCKET_ERROR) { cout << "connect error:" << WSAGetLastError() << endl; return 0; } //3接受发送消息 int ret = 0; do { char buf[64] = {'\0'}; ret = recv(s,buf,64,0); cout << "recv:" << inet_ntoa(addr.sin_addr) << ": " << buf << endl; //send ret = send(s,"i am client!",strlen("i am client!"),0); Sleep(1000); } while (ret != SOCKET_ERROR && ret != 0); //清理winsock环境 WSACleanup(); //netstat -ao return 0; }