Socket 简单的代码实现

Posted blogwww

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Socket 简单的代码实现相关的知识,希望对你有一定的参考价值。

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
");
  SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len); //服务端会在此一直等到客户端连接,只有客户端连接成功后,才会执行后续语句
  printf("have a client connecting
");
  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
",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
",recvBuf);
 
 closesocket(sockClient);
 WSACleanup();
	return 0;
}

 

以上是关于Socket 简单的代码实现的主要内容,如果未能解决你的问题,请参考以下文章

SOCKET简单爬虫实现代码和使用方法

Socket 简单的代码实现

Socket编程的简单实现

简单的通信----使用Socket实现TCP协议

Java实现简单的socket通信

java代码实现socket接口通讯(堵塞I/O)