TCP客服端代码

这两天在看网络编程,写了点程序,发给大家看看.

首先看看流程:
TCP客服端代码_第1张图片

然后直接上代码:
下面是客户端代码,如果想了解服务器端的代码请查看
https://blog.csdn.net/u011394598/article/details/83110014

#include 
#include 
using namespace std;

#define SERVER_IP "192.168.0.168"		//本地tcp服务器IP
#define SERVER_PORT 60008				//本地tcp服务器端口

void main()
{
	//加载套接字  
	try
	{
		WORD sockVersion = MAKEWORD(2, 2);
		WSADATA wsaData;
		int result = WSAStartup(sockVersion, &wsaData);
		if (0 != result)
		{
			return ;
		}

		if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
		{
			WSACleanup();
			return ;
		}
	}
	catch (...)
	{
		return ;
	}

	char buff[1024];
	memset(buff, 0, sizeof(buff));

	//创建套接字  
	//SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);
	SOCKET sockClient = NULL;
	try
	{
		sockClient = socket(AF_INET, SOCK_STREAM, 0);

		if (sockClient == INVALID_SOCKET)
		{
			return ;
		}
	}
	catch (...)
	{
		return ;
	}

	SOCKADDR_IN addrSrv;
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(60008);
	addrSrv.sin_addr.S_un.S_addr = inet_addr("192.168.0.168");


	if (SOCKET_ERROR == sockClient){
		printf("Socket() error:%d", WSAGetLastError());
		return;
	}

	//向服务器发出连接请求  
	if (connect(sockClient, (struct  sockaddr*)&addrSrv, sizeof(addrSrv)) == INVALID_SOCKET){
		printf("Connect failed:%d", WSAGetLastError());
		return;
	}

	while (1)
	{
		//接收数据  
		recv(sockClient, buff, sizeof(buff), 0);
		printf("%s\n", buff);
		//发送数据  
		char buff1[] = "hello, this is a Client....";
		send(sockClient, buff1, sizeof(buff1), 0);
	}

	//发送数据  
	char buff1[] = "hello, this is a Client....";
	send(sockClient, buff1, sizeof(buff1), 0);

	//关闭套接字  
	closesocket(sockClient);
	WSACleanup();
}

你可能感兴趣的:(C++)