最基本的TCP客户端


// SimpleTCPClient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <winsock2.h>
#include <stdio.h>

#pragma comment (lib, "Ws2_32.lib")

#define BUF_SIZE 64

int _tmain(int argc, _TCHAR* argv[])
{
	//初始化socket库
	WSADATA wsd;
	if(WSAStartup(MAKEWORD(2,2), &wsd) != 0)
	{
		printf("WSAStartup failed!\n");
		return -1;
	}

	SOCKET sHost = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(INVALID_SOCKET == sHost)
	{
		printf("socket failed!\n");
		WSACleanup();
		return -1;
	}

	SOCKADDR_IN servAddr;
	servAddr.sin_family = AF_INET;
	servAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	servAddr.sin_port = htons((short)4999);
	int nServAddlen = sizeof(servAddr);

	int retVal = connect(sHost, (LPSOCKADDR)&servAddr, sizeof(servAddr));
	if(SOCKET_ERROR == retVal)
	{
		printf("connect failed!\n");
		closesocket(sHost);
		WSACleanup();
		return -1;
	}

	char buf[BUF_SIZE];
	ZeroMemory(buf, BUF_SIZE);
	strcpy(buf, "MyTCP");
	retVal = send(sHost, buf, strlen(buf), 0);
	if(SOCKET_ERROR == retVal)
	{
		printf("send failed!\n");
		closesocket(sHost);
		WSACleanup();
		return -1;
	}

	closesocket(sHost);
	WSACleanup();

	return 0;
}



你可能感兴趣的:(tcp,Stream,socket)