首页 > 其他 > 详细

Socket (二) 简单的代码实现

时间:2018-08-21 00:05:41      阅读:222      评论:0      收藏:0      [点我收藏+]

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 (二) 简单的代码实现

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!