// client.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "client.h"#ifdef _DEBUG#define new DEBUG_NEW#endif#include"Winsock2.h"#include"stdio.h"#include"stdlib.h"#include"stdafx.h"#define DEFAULT_PORT 5050 //服务器端口号为5050#define DATA_BUFFER 1024// 唯一的应用程序对象CWinApp theApp;using namespace std;int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]){int nRetCode = 0;// 初始化 MFC 并在失败时显示错误if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)){// TODO: 更改错误代码以符合您的需要_tprintf(_T("错误: MFC 初始化失败\n"));nRetCode = 1;}else{// TODO: 在此处为应用程序的行为编写代码。}return nRetCode;}void main(int argc,char *argv[]){WSADATA wsaData;SOCKET sClient;int iPort=DEFAULT_PORT;int iLen; //从服务器接受的数据长度char buf[DATA_BUFFER];struct sockaddr_in ser; //判断输入是否正确if(argc<2){printf("Usage:client[server IP address]\n"); //提示在命令中输入服务器IP地址return;}//接收数据的缓冲初始化memset(buf,0,sizeof(buf));if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0){printf("Failed to load Winsock.\n");return;}//填写要连接的服务器地址信息ser.sin_family=AF_INET; ser.sin_port=htons(iPort);ser.sin_addr.s_addr=inet_addr(argv[1]); //inet_addr()函数将命令行的点分IP地址转化为用二进制表示的网络字节顺序的IP地址//建立客户端流式套接口sClient=socket(AF_INET,SOCK_STREAM,0);if(sClient==INVALID_SOCKET){printf("socket()Failed:%d\n",WSAGetLastError());return;}//请求与服务器端建立TCP连接if(connect(sClient,(struct sockaddr*)&ser,sizeof(ser))==INVALID_SOCKET){printf("connect()Failed:%d\n",WSAGetLastError());return;}else{//从服务器端接受数据iLen=recv(sClient,buf,sizeof(buf),0);if(iLen==0)return;else if(iLen==SOCKET_ERROR){printf("rev()Failed:%d\n",WSAGetLastError());return;}printf("recv()data from server:%s\n",buf);}closesocket(sClient);WSACleanup();}C++控制台程序Win32 Console Application是基于TCP的通信程序(客户端)
- 1 回答
- 0 关注
- 91 浏览
添加回答
举报
0/150
提交
取消