关闭

简单的UDP回射服务程序与客户程序(修改自Unix网络编程一书)

759人阅读 评论(0) 收藏 举报
#include<winsock2.h>
#include"InitSock.h"
#include<windows.h> 
#include<cstdio>
#include<cstdlib>
#include<cstring>



#pragma comment(lib,"ws2_32.lib")

CInitSock InitSock ;

#define SERVERPORT  5010


void dg_echo(SOCKET sSockfd , SOCKADDR * pcliaddr, size_t clilen) ;

int main(void)
{
	SOCKET sSockfd ;
	sockaddr_in  Servaddr , Cliaddr ;

	sSockfd = socket(AF_INET,SOCK_DGRAM,0) ;

	memset(&Servaddr,0,sizeof(Servaddr)) ;
	memset(&Cliaddr,0,sizeof(Cliaddr)) ;

	Servaddr.sin_family = AF_INET ;
	Servaddr.sin_port = htons(SERVERPORT) ;
	Servaddr.sin_addr.s_addr = htonl(INADDR_ANY) ;

	bind(sSockfd,(SOCKADDR *)&Servaddr, sizeof(Servaddr)) ;

	dg_echo(sSockfd,(SOCKADDR*) &Cliaddr ,sizeof(Cliaddr)) ;


	return  0 ;
}

void dg_echo(SOCKET sSockfd , SOCKADDR * pcliaddr, size_t clilen)
{
	int n = 0 ;
	int iSend = 0 ;

	int len = 0 ;

	TCHAR szRecvMsg[1024] ;
	TCHAR szSendMsg[1024]  ;
	
	for(; ; )
	{
		len = clilen ;
		n = recvfrom(sSockfd,szRecvMsg,1024,0,pcliaddr,&len) ;
		szRecvMsg[n] = '\0' ;

		printf("接收到 %d 字节数据,内容为 %s\n",n , szRecvMsg) ;

		strcpy(szSendMsg,szRecvMsg) ;
		iSend = sendto(sSockfd,szSendMsg,strlen(szSendMsg),0,pcliaddr,len) ;

		printf("发送到 %d 字节数据,内容为 %s\n",iSend,szSendMsg) ;

	}
}


 

 

#include<winsock2.h>
#include"InitSock.h"
#include<windows.h>
#include<cstdio>
#include<cstdlib>
#include<cstring>


#pragma comment(lib,"ws2_32.lib") 

CInitSock InitSock ;

#define SERVERPORT  5010


void dg_cli(FILE *fp,SOCKET sockfd, const SOCKADDR * pservaddr, int servlen)  ; 

int main(void)
{
	SOCKET  sSockClient ;
	sockaddr_in  Servaddr ;

	memset(&Servaddr,0,sizeof(Servaddr)) ;

	Servaddr.sin_family = AF_INET ;
	Servaddr.sin_port = htons(SERVERPORT) ;
	Servaddr.sin_addr.s_addr = inet_addr("127.0.0.1") ;

	sSockClient = socket(AF_INET,SOCK_DGRAM,0) ;

	dg_cli(stdin,sSockClient,(SOCKADDR*) &Servaddr,sizeof(Servaddr)) ;

	return  0 ;
}

void dg_cli(FILE *fp,SOCKET sockfd, const SOCKADDR * pservaddr, int servlen)
{
	int iRecv = 0 ;
	int iSend = 0 ;
	TCHAR  szSendMsg[1024]  ;
	TCHAR szRecvMsg[1024]  ;

	while(fgets(szSendMsg,1024,fp) != NULL)
	{
		iSend = sendto(sockfd,szSendMsg,strlen(szSendMsg),0,pservaddr,servlen) ;

		iRecv = recvfrom(sockfd,szRecvMsg,1024,0,NULL,NULL) ;

		szRecvMsg[iRecv] = '\0' ;

		printf("回显数据: \n") ;
		fputs(szRecvMsg,stdout) ;
	}
	
}


 

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:317316次
    • 积分:4039
    • 等级:
    • 排名:第7714名
    • 原创:112篇
    • 转载:58篇
    • 译文:0篇
    • 评论:72条
    最新评论