Client

龙高超
2023-12-01
// Client.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <Windows.h>
#include <vector>
#include <algorithm>
using namespace std;
#pragma comment(lib,"ws2_32.lib")


int initWSA()
{
	WSADATA wsaData;
	if(0!=WSAStartup(MAKEWORD(2,2),&wsaData))
	{
		printf("初始化网络失败错误代码 =%d",WSAGetLastError());
		WSACleanup();
		return 0;
	}

	printf("网络环境初始化成功!");
	return 1;

}


SOCKET createSocket()
{
	SOCKET serverSocket =socket(AF_INET,SOCK_STREAM,0);
	if (serverSocket == INVALID_SOCKET )
	{
		printf("创建套接字失败!错误代码=%d",WSAGetLastError());
		closesocket(serverSocket);
	}
	else
		printf("创建套接字成功!\n");
	return serverSocket;

}

void sendBuff(SOCKET s,char* buf,int len)
{

	int dataLen = len;
	int sendLen =0;
	int sendCount =0;
	while(dataLen>0)
	{
		sendLen = send(s,buf+sendCount,dataLen-sendLen,0);
		if (sendLen==SOCKET_ERROR )
		{
			printf("发送给客户端出错\n");
			break;
		}
		if (sendLen ==0)
		{
			printf("客户端已经关闭\n");
			break;
		}
		sendCount+=sendLen;
		dataLen-=sendLen;
	}
}

void recvData(SOCKET s,char* buf, int len)
{
	int countDatalen=0;
	char buff[2048];
	int recvLen =0;
	while(1)
	{
		if (countDatalen>2048)
		{
			printf("数据太大!\n");
			break;;
		}
		recvLen =recv(s,buff+countDatalen,sizeof(buff)-countDatalen,0);
		countDatalen+=recvLen;
		if (recvLen ==0)
		{
			printf("服务器socket已经关闭\n");
			break;
		}
		else if (recvLen<sizeof(buff))
		{
			printf("数据接收完成!\n");
			break;;
		}
	}

	memcpy(buf,buff,countDatalen);
}

int _tmain(int argc, _TCHAR* argv[])
{
	if (!initWSA())
		goto mark;

	SOCKET ServerSocket = createSocket();
	if (ServerSocket == INVALID_SOCKET)
		goto mark;


	SOCKADDR_IN serverInfo;
	serverInfo.sin_family = AF_INET;
	serverInfo.sin_port = htons(9100);
	serverInfo.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	int infoLen = sizeof(serverInfo);

	int err = connect(ServerSocket,(SOCKADDR*)&serverInfo,infoLen);
	if (err == SOCKET_ERROR)
	{
		printf("连接服务器出错,错误代码=%d",WSAGetLastError());
		goto mark;
	}
	char buf[] ="你好服务器";
	sendBuff(ServerSocket,buf,sizeof(buf));

	char recvBuf[2024];
	recvData(ServerSocket,recvBuf,2024);
	printf("服务器发来%s",recvBuf);
	
mark: system("pause");
	WSACleanup();
	closesocket(ServerSocket);
	return 0;
}

 类似资料: