创建TCP客户端

#include<iostream>
#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

// Need to link with Ws2_32.lib
#pragma comment(lib, "ws2_32.lib")

using namespace std;
int main()
{

	
	//1.加载库 --WSAStartup;
	 WORD wVersionRequested;
    WSADATA wsaData;
    int err;

/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {
        /* Tell the user that we could not find a usable */
        /* Winsock DLL.                                  */
        printf("WSAStartup failed with error: %d\n", err);
        return 1;
    }

/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater    */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we      */
/* requested.                                        */

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
        /* Tell the user that we could not find a usable */
        /* WinSock DLL.                                  */
        printf("Could not find a usable version of Winsock.dll\n");
        WSACleanup();
        return 1;
    }
    else
        printf("The Winsock 2.2 dll was found okay\n");
	//2.socket();
	SOCKET C_client=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(C_client==INVALID_SOCKET)
	{
		WSACleanup();
        return 1;
	}
	//3.connect();
	sockaddr_in  adder;
	adder.sin_family=AF_INET;
	adder.sin_addr.S_un.S_addr=inet_addr("127.1.1.1");//网址
	adder.sin_port=htons(27015);
	if(connect(C_client,(const sockaddr *)&adder,sizeof(adder))==SOCKET_ERROR)
	{
		closesocket(C_client);
		WSACleanup();
        return 1;
	}
	//4.send();
	char bufz[1024]={0};
	cin>>bufz;
	send(C_client,bufz,sizeof(bufz),0);
	//5.recv();
	int RecNum=recv(C_client,bufz,sizeof(bufz),0);
	if(RecNum>0)
	{
cout<<bufz<<endl;
	}
	//6.closesocket();
	closesocket(C_client);
	WSACleanup();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值