TCPClient代码

TCPClient代码

#include <iostream>

#include <winsock2.h>

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

using namespace std;

int main()
{
	//1.加载库 
	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 sockClient =  socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(INVALID_SOCKET == sockClient)
	{
		 WSACleanup();
         return 1;
	}
	//3.找地方(连接服务器)
	sockaddr_in addrServer;
	addrServer.sin_family = AF_INET;//地址族
	addrServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//服务器地址
	addrServer.sin_port = htons(1234);//端口号
	if(SOCKET_ERROR == connect(sockClient,(const sockaddr*)&addrServer,sizeof(sockaddr_in)))
	{
		 closesocket(sockClient);
		 WSACleanup();
         return 1;
	}

	//4.发送数据
	char szbuf[100] = {0};
	while(1)
	{
		cin>>szbuf;
		send(sockClient,szbuf,sizeof(szbuf),0);
	5.接收数据
	//int nRel = recv(sockClient,szbuf,sizeof(szbuf),0);
	//if(nRel >0)
	//{
	//	cout<<szbuf<<endl;
	//}
	}
	
	


	//关闭套接字、卸载库
	closesocket(sockClient);
	WSACleanup();

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值