C++客戶端程式(socket)

露水上的青蛙發表於2013-07-02

// MyClient.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include "stdio.h"
#include "Winsock2.h"
#include "conio.h"
#include "stdlib.h"
#pragma comment(lib,"ws2_32.lib")

void BeginSend(char *sendBuf)
{
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;

 wVersionRequested = MAKEWORD(1,1);

 err = WSAStartup(wVersionRequested,&wsaData);
 if(err!=0){
  exit(0);
 }
 if(LOBYTE(wsaData.wVersion)!=1||
  HIBYTE(wsaData.wVersion)!=1){
   WSACleanup();
   exit(0);
 }

 SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);

 SOCKADDR_IN addrSrv;
 addrSrv.sin_addr.S_un.S_addr=inet_addr("130.234.1.92");
 addrSrv.sin_family=AF_INET;
 addrSrv.sin_port=htons(5101);
 connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
// char sendBuf[50];

    send(sockClient,sendBuf,strlen(sendBuf),0);

/* char recvBuf[50];
 recv(sockClient,recvBuf,50,0);
 printf("%s\n",recvBuf);*/

 closesocket(sockClient);
 WSACleanup();
}

int _tmain(int argc, _TCHAR* argv[])
{
 char sendBuf[100];
 while (true)
 {
  printf("Please input a value:");
  scanf("%s",sendBuf);
  BeginSend(sendBuf);
  printf("%s\n",sendBuf);
 }
   
 return 0;
}

相關文章