//客户端 #include"mysocket.h" //头文件 using namespace std; int main() { cout << "-----------------客户端----------------\n"; startup(); //启动 //检测版本号 if (LOBYTE(wsdata.wVersion) != 2 || HIBYTE(wsdata.wHighVersion) != 2) { cout << "版本号与服务端不匹配!" << endl; WSACleanup(); return FALSE; } //填充服务端信息:这里填和服务端一样的就好,不做解释 SOCKET client = createSocket(PF_INET, SOCK_STREAM); SOCKADDR_IN server_addr; server_addr.sin_family = AF_INET; server_addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.25"); server_addr.sin_port = htons(1000); //发送连接请求 请求连接服务器 if (connect(client, (SOCKADDR*)&server_addr, sizeof(SOCKADDR)) == SOCKET_ERROR) { cout << "连接错误!" << endl; WSACleanup(); return -1; } cout << "成功连接到服务器" << endl; char send_buf[1145], recv_buf[4514]; while(1){ cout << "输入要发送的信息:"; cin >> send_buf; mysend(client, send_buf); cout << "等待服务端响应...\n"; myrecv(client, recv_buf); cout << "收到来自服务端的信息:" << recv_buf << endl; } return 0; }
//mysocket.h #ifndef __MYSOCKET_H__ #define __MYSOCKET_H__ //头文件保护 #include<bits/stdc++.h> #include<winsock.h> #pragma comment(lib,"ws2_32.lib") using namespace std; WSADATA wsdata; void startup(){ //异步启动 if (WSAStartup(MAKEWORD(2, 2), &wsdata)) /* ^ ^ 版本号,这里用的是2.2 | 数据存放处,这里设成全局变量 */ { //返回0则成功,否则失败,报错 cout << "启动失败!\n"; WSACleanup(); exit(0); } } SOCKET createSocket(int af, int type){ /*原函数原型: SOCKET socket(int af, int type, int protocol) ^ ^ ^ 协议 类型(后文) 形式(一般用0) */ SOCKET ret = socket(af, type, 0); if (ret == INVALID_SOCKET) //错误返回INVALID_SOCKET { //报错 cout << "创建套接字失败!\n"; WSACleanup(); exit(0); } return ret; } void mysend(SOCKET s, const char* buf){ /* 带报错的send()函数,原函数原型为 : int send(SOCKET s, const char* buf, int len, int flag) 这里为了简化,省略后两个参数。 函数把buf发送给s,返回发送长度 */ int len = send(s, buf, sizeof(buf), 0); if(len < 0) //发送错误 { cout << "信息发送失败!\n"; WSACleanup(); exit(0); } } void myrecv(SOCKET s, char* buf){ /* 带报错的recv()函数,其原型为: int recv(SOCKET s, char* buf, int len, int flag) 同样省略后两个参数 函数将从s收到的信息储存在buf中,返回接收长度 */ int len = recv(s, buf, sizeof(buf), 0); if(len < 0) { cout << "信息接收失败!\n"; WSACleanup(); exit(0); } } #endif //别忘了
标签:__,cout,lib,mysocket,namespace,信息,客户,include From: https://www.cnblogs.com/liujiaxing-/p/18238343