网络编程实验2_(3)基于流式套接字的客户端程序设计

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <iostream>
#include <winsock2.h>

using namespace std;

#pragma comment(lib, "ws2_32.lib")

#define PORT 7210
#define IP_ADDRESS "192.168.0.103"
//先用cmd命令行——ipconfig查一下自己的ip地址 #define MAX_LINE 10000 int main(int argc, char* argv[]) { WSADATA wsaData; SOCKET ClientSocket; struct sockaddr_in ServerAddr; int iResult = 0; int AddrLen = 0; HANDLE hThread = NULL; char SendBuffer[MAX_LINE]; //初始化 Windows Socket if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { cout << "Windows Socket 初始化失败::" << GetLastError() << endl; WSACleanup(); return -1; } //创建 Socket ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ClientSocket == INVALID_SOCKET) { cout << "Socket创建失败::" << GetLastError() << endl; closesocket(ClientSocket); WSACleanup(); return -1; } ServerAddr.sin_family = AF_INET; ServerAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS); ServerAddr.sin_port = htons(PORT); memset(ServerAddr.sin_zero, 0x00, 8); //这个有两种方法, //一种是像这样给ServerAddr中的前三个参数逐一赋值后,最后给sin_zero填充0 //还有一种是,先用memset(&ServerAddr,0,sizeof(ServerAddr))对整个变量零填充,再对前三个参数逐一赋值 /* memset(&ServerAddr, 0, sizeof(ServerAddr)); ServerAddr.sin_family = AF_INET; ServerAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS); ServerAddr.sin_port = htons(PORT); */ //connect //一个细节:connect的第二个参数ServerAddr设置为sockaddr_in类型的变量, //然后再connect中应当将其强转为sockaddr类型 iResult = connect(ClientSocket, (struct sockaddr*) & ServerAddr, sizeof(ServerAddr)); if (iResult == SOCKET_ERROR) { cout << "Connect Error::" << GetLastError() << endl; WSACleanup(); return -1; } else { cout << "连接成功!" << endl; } char RecvBuffer[MAX_LINE];//接收到的信息 while (true) { cin.getline(SendBuffer, sizeof(SendBuffer),'$'); iResult = send(ClientSocket, SendBuffer, (int)strlen(SendBuffer), 0); if (iResult == SOCKET_ERROR) { cout << "Send Info Error::" << GetLastError() << endl; break; } memset(RecvBuffer, 0x00, sizeof(RecvBuffer)); //初始化,每个字节都用0填充 iResult = recv(ClientSocket, RecvBuffer, MAX_LINE, 0); //接收服务器返回的信息 cout << "接收到服务器信息为:" << RecvBuffer << endl; //输出接收到的信息 } closesocket(ClientSocket); WSACleanup(); return 0; }

 

posted @ 2020-03-23 20:43  chuyaoxin  阅读(500)  评论(0编辑  收藏  举报