最基本的TCP服务端


// SimpleTCPServer.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[])
{
	WSADATA wsd;
	SOCKET  sServer;
	int retVal;

	if(WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
	{
		printf("WSAStartup failed!");
		return 1;
	}
	
	sServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(INVALID_SOCKET == sServer)
	{
		printf("socket failed!");
		WSACleanup();
		return 1;
	}

	SOCKADDR_IN addrServ;
	addrServ.sin_family = AF_INET;
	addrServ.sin_port = htons(5900);
	addrServ.sin_addr.S_un.S_addr = INADDR_ANY;

	retVal = bind(sServer, (LPSOCKADDR)&addrServ, sizeof(SOCKADDR_IN));
	if(SOCKET_ERROR == retVal)
	{
		printf("bind failed!\n");
		closesocket(sServer);
		WSACleanup();
		return -1;
	}

	retVal = listen(sServer, 1);
	if(SOCKET_ERROR == retVal)
	{
		printf("listen failed!\n");
		closesocket(sServer);
		WSACleanup();
		return -1;
	}

	sockaddr_in addrClient;
	int addrClientLen = sizeof(addrClient);
	SOCKET sClient = accept(sServer, (sockaddr FAR*)&addrClient, &addrClientLen);
	if(INVALID_SOCKET == sClient)
	{
		printf("accept failed!\n");
		closesocket(sServer);
		WSACleanup();
		return -1;
	}

	char buf[BUF_SIZE];
	ZeroMemory(buf, BUF_SIZE);
	retVal = recv(sClient, buf, BUF_SIZE, 0);
	if(INVALID_SOCKET == retVal)
	{
		printf("reev failed!\n");
		closesocket(sServer);
		closesocket(sClient);
		WSACleanup();
		return -1;
	}

	closesocket(sServer);
	closesocket(sClient);

	return 0;
}


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