码迷,mamicode.com
首页 > 其他好文 > 详细

Socket (二) 简单的代码实现

时间:2018-08-21 00:24:50      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:start   listen   net   clean   inet_ntoa   comm   cli   requested   wsad   

SocktServer.cpp

#include "stdafx.h"
#pragma comment(lib,"ws2_32.lib")
#include <Winsock2.h> 

int _tmain(int argc, _TCHAR* argv[])
{
	WORD wVersionRequested; 
 WSADATA wsaData; 
 int err; 
   
 wVersionRequested = MAKEWORD( 1, 1 ); 
   
 err = WSAStartup( wVersionRequested, &wsaData ); 
 if ( err != 0 ) { 
  return 0; 
 } 
   
 if ( LOBYTE( wsaData.wVersion ) != 1 || 
        HIBYTE( wsaData.wVersion ) != 1 ) { 
  WSACleanup( ); 
  return 0; 
 } 
 SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0); 
  
 SOCKADDR_IN addrSrv; 
 addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY); 
 addrSrv.sin_family=AF_INET; 
 addrSrv.sin_port=htons(8080); 
   
 bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); 
  
 listen(sockSrv,5); 
  
 SOCKADDR_IN addrClient; 
 int len=sizeof(SOCKADDR); 
 while(1) 
 { 
  printf("in while\n");
  SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len); //服务端会在此一直等到客户端连接,只有客户端连接成功后,才会执行后续语句
  printf("have a client connecting\n");
  char sendBuf[50]; 
  sprintf(sendBuf,"Welcome %s ",inet_ntoa(addrClient.sin_addr)); 
  send(sockConn,sendBuf,strlen(sendBuf)+1,0); 
  char recvBuf[50]; 

  for (int j = 0; j < 50; j++)
  {
	  recvBuf[j] = NULL;
  }
  recv(sockConn,recvBuf,50,0); 

  printf("%s\n",recvBuf); 
  closesocket(sockConn); 
 } 
  
	return 0;
}

 SocktClient.cpp

#include "stdafx.h"
#pragma comment(lib,"ws2_32.lib")
#include <Winsock2.h> 

int _tmain(int argc, _TCHAR* argv[])
{
	WORD wVersionRequested;
 WSADATA wsaData;
 int err;
 
 wVersionRequested = MAKEWORD( 1, 1 );
 
 err = WSAStartup( wVersionRequested, &wsaData );
 if ( err != 0 ) {
  return 0;
 }
 
 if ( LOBYTE( wsaData.wVersion ) != 1 ||
        HIBYTE( wsaData.wVersion ) != 1 ) {
  WSACleanup( );
  return 0;
 }
 SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);
 
 SOCKADDR_IN addrSrv;
 addrSrv.sin_addr.S_un.S_addr=inet_addr("192.168.0.127");
 addrSrv.sin_family=AF_INET;
 addrSrv.sin_port=htons(8080);
 connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
 send(sockClient,"00000",strlen("11111 ")+1,0);
 char recvBuf[50];
 recv(sockClient,recvBuf,50,0);
 printf("%s\n",recvBuf);
 
 closesocket(sockClient);
 WSACleanup();
	return 0;
}

 

Socket (二) 简单的代码实现

标签:start   listen   net   clean   inet_ntoa   comm   cli   requested   wsad   

原文地址:https://www.cnblogs.com/blogwww/p/9508904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!