简单Socket程序

// SocketServer.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
 WSADATA wsd;
    SOCKET sServer;
 SOCKET sClient;
 sockaddr_in addrServ;
 sockaddr_in addrClient;
 int retval;

 if(WSAStartup(MAKEWORD(2,2),&wsd) != 0)
 {
        printf("WSAStartup fail!");
  getchar();
  WSACleanup();
  return 0;
 }
 //创建SOCKET
 sServer = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
 if(INVALID_SOCKET == sServer)
 {
  printf("create socket fail!");
  getchar();
  WSACleanup();
  return 0;
 }

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

 retval = bind(sServer,(struct sockaddr *)&addrServ,sizeof(struct sockaddr));
 if(SOCKET_ERROR == retval)
 {
  printf("bind fail!");
  getchar();
  closesocket(sServer);
  WSACleanup();
  return 0;
 }
 //监听
 retval = listen(sServer,1);
 if(SOCKET_ERROR == retval)
 {
  printf("listen fail!");
  getchar();
  closesocket(sServer);
  WSACleanup();
  return 0;
 }

 int addrClentlen = sizeof(sockaddr_in);
 sClient = accept(sServer,(struct sockaddr *)&addrClient,&addrClentlen);
 if(INVALID_SOCKET == sClient)
 {
  printf("accept fail!");
  getchar();
  closesocket(sServer);
  WSACleanup();
  return 0;
 }
    const int BUF_SIZE = 255;
 char buf[BUF_SIZE];
 ZeroMemory(buf,BUF_SIZE);
 retval = recv(sClient,buf,BUF_SIZE,0);
 if(retval == SOCKET_ERROR)
 {
  printf("recv fail!");
  closesocket(sClient);
  closesocket(sServer);
  WSACleanup();
  getchar();
  return 0;
 }
 printf("%s",buf);
 getchar();
 return 0;
}

 

// SocketClient.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#define BUF_SIZE 64

int _tmain(int argc, _TCHAR* argv[])
{
    WSADATA wsd;
 SOCKET sClient;
 int retval;
 sockaddr_in addrServer;
 char buf[BUF_SIZE];

 if(WSAStartup(MAKEWORD(2,2),&wsd) != 0)
 {
  printf("WSAStartup fail!");
  getchar();
  return 0;
 }
   
 sClient = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
 if(INVALID_SOCKET == sClient)
 {
  printf("create socket fail!");
  getchar();
  WSACleanup();
  return -1;
 }
 addrServer.sin_family = AF_INET;
 addrServer.sin_port = htons(4999);
 addrServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
 //连接服务器
 retval = connect(sClient,(struct sockaddr *)&addrServer,sizeof(addrServer));
 if(SOCKET_ERROR == retval)
 {
  printf("connect fail!");
  getchar();
  closesocket(sClient);
  WSACleanup();
  return -1;
 }

 //发送数据
 ZeroMemory(buf,BUF_SIZE);
 strcpy(buf,"Hello,TCP!");
 retval = send(sClient,buf,strlen(buf),0);
 if(retval == SOCKET_ERROR)
 {
  printf("send fail!");
  getchar();
  closesocket(sClient);
  WSACleanup();
  return -1;
 }
 getchar();
 //退出
 closesocket(sClient);
 WSACleanup();
 
 return 0;
}

 

 

你可能感兴趣的:(编程,socket,职场,休闲)