⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serverdlg.cpp

📁 利用rtp库实现实时语音传送
💻 CPP
字号:
// ServerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Server.h"
#include "ServerDlg.h"
#include <crtdbg.h> //for _ASSERT
#include "string.h"
//JRTP includes

//#include "RTPIPv4Address.h"
//#include "RTPSessionParams.h"
//#include "RTPUDPv4Transmitter.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define MCAST_IP		"239.216.30.54"
#define MCAST_PORT		4000
#define SERVER_PORT		5000
#define LOCAL_IP		"172.16.129.86"

#define MAX_PACKET_SIZE	((1024 * 64) - 1)

/////////////////////////////////////////////////////////////////////////////
// CServerDlg dialog

CServerDlg::CServerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CServerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CServerDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CServerDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CServerDlg, CDialog)
	//{{AFX_MSG_MAP(CServerDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTOPEN, OnButOpen)
	ON_BN_CLICKED(IDC_BUTSTART, OnButStart)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CServerDlg message handlers

BOOL CServerDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	WSADATA	wsaData;
	if(WSAStartup(MAKEWORD(2,2),&wsaData) != 0)
	{
		return FALSE;
	};
	unsigned long addr = ntohl(inet_addr("172.16.129.86"));
	int nRet;
	nRet = m_rtpSession.Create(10002);
	nRet = m_rtpSession.AddDestination(addr,10000);
	nRet = m_rtpSession.SetMaxPacketSize(60000);
	m_rtpSession.SetDefaultPayloadType(0);
	m_rtpSession.SetDefaultMark(false);
	m_rtpSession.SetDefaultTimeStampIncrement(10);
	m_hPollDataThrd = NULL;
	m_bRunThread = FALSE;
	m_hMediaFile = INVALID_HANDLE_VALUE;
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CServerDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CServerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}
/*
void CServerDlg::OnButOpen() 
{
	// TODO: Add your control notification handler code here
	OPENFILENAME  ofn ;
	TCHAR         achFileName[MAX_PATH] ;
	ZeroMemory(achFileName,MAX_PATH);
	// Init the filename buffer with either a filename or *.ifo
	ZeroMemory(&ofn, sizeof(OPENFILENAME)) ;
	ofn.lStructSize = sizeof(OPENFILENAME) ;
	ofn.hwndOwner = m_hWnd ;
	ofn.lpstrTitle = TEXT("Select Media File\0") ;
	ofn.lpstrFilter = TEXT("MPEG Files\0*.*;*.*\0\0") ;
	
	ofn.nFilterIndex = 1 ;
	ofn.lpstrFile = achFileName ;
	ofn.nMaxFile = sizeof(achFileName) ;
	ofn.lpstrFileTitle = NULL ;
	ofn.nMaxFileTitle = 0 ;
	ofn.lpstrInitialDir = NULL ;
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_HIDEREADONLY ;
	
	if (!GetOpenFileName(&ofn)) // user specified a file
	{
		return ;
	}

	SetDlgItemText(IDC_CURPLAYING,achFileName);
	if(m_hMediaFile!=INVALID_HANDLE_VALUE)
		CloseHandle(m_hMediaFile);
	m_hMediaFile = CreateFile(achFileName,
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,OPEN_EXISTING,0,NULL);
	CURRENCY len;
	len.Lo = GetFileSize(m_hMediaFile,(LPDWORD)&len.Hi);
	m_llMediaLen = len.int64;
}*/
void CServerDlg::OnButOpen() 
{
	// TODO: Add your control notification handler code here
	OPENFILENAME  ofn ;
	TCHAR         achFileName[MAX_PATH] ;
	ZeroMemory(achFileName,MAX_PATH);
	// Init the filename buffer with either a filename or *.ifo
	ZeroMemory(&ofn, sizeof(OPENFILENAME)) ;
	ofn.lStructSize = sizeof(OPENFILENAME) ;
	ofn.hwndOwner = m_hWnd ;
	ofn.lpstrTitle = TEXT("Select Media File\0") ;
	ofn.lpstrFilter = TEXT("Mpeg Files (*.mpg;*.mpeg)|*.mpg; *.mpeg|") ;
	
	ofn.nFilterIndex = 1 ;
	ofn.lpstrFile = achFileName ;
	ofn.nMaxFile = sizeof(achFileName) ;
	ofn.lpstrFileTitle = NULL ;
	ofn.nMaxFileTitle = 0 ;
	ofn.lpstrInitialDir = NULL ;
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_HIDEREADONLY ;
	
	if (!GetOpenFileName(&ofn)) // user specified a file
	{
		return ;
	}

	SetDlgItemText(IDC_CURPLAYING,achFileName);
	if(m_hMediaFile!=INVALID_HANDLE_VALUE)
		CloseHandle(m_hMediaFile);
	m_hMediaFile = CreateFile(achFileName,
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,OPEN_EXISTING,0,NULL);
	CURRENCY len;
	len.Lo = GetFileSize(m_hMediaFile,(LPDWORD)&len.Hi);
	if(len.Lo>12)
		MessageBox("file ok");
	m_llMediaLen = len.int64;
}
/*
void CServerDlg::OnButOpen() 
{
	CFileDialog  dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, 
			"Mpeg Files (*.mpg;*.mpeg)|*.mpg; *.mpeg|", NULL);
	if (dlg.DoModal() == IDOK)
	{
		m_strSourceFile = dlg.GetPathName();
		ListenOnConnection();
	}
}
*/
/*
void CServerDlg::OnButStart() 
{
	 int status;
 
  // 获得接收端的IP地址和端口号
 	unsigned long localIP = inet_addr(LOCAL_IP);
		_ASSERT(localIP != INADDR_NONE);
  // 创建RTP会话
  status = m_rtpSession.Create(SERVER_PORT,localIP);
 // checkerror(status);

//  MessageBox("error1");
	unsigned long intIP = inet_addr(MCAST_IP);
	_ASSERT(intIP != INADDR_NONE);
	intIP = ntohl(intIP); //put in host byt
  // 指定RTP数据接收端
  status = m_rtpSession.AddDestination(intIP, MCAST_PORT);

  // 设置RTP会话默认参数
  m_rtpSession.SetDefaultPayloadType(0);
  m_rtpSession.SetDefaultMark(false);
  m_rtpSession.SetDefaultTimeStampIncrement(10);
	// TODO: Add your control notification handler code here
	if(m_hPollDataThrd != NULL)
		return ;
	DWORD dwThreadId;
	m_hPollDataThrd = CreateThread(NULL,
                     0,
                     PollDataProc,
                     (LPVOID)this,
                     0,
                     &dwThreadId);
	if(!m_hPollDataThrd)
	{
		m_hPollDataThrd = NULL;
		m_bRunThread = FALSE;
		return ;
	}
	m_bRunThread = TRUE;
}
*/
void CServerDlg::OnButStart() 
{
	// TODO: Add your control notification handler code here
	if(m_hPollDataThrd != NULL)
		return ;
	DWORD dwThreadId;
	m_hPollDataThrd = CreateThread(NULL,
                     0,
                     PollDataProc,
                     (LPVOID)this,
                     0,
                     &dwThreadId);
	if(!m_hPollDataThrd)
	{
		m_hPollDataThrd = NULL;
		m_bRunThread = FALSE;
		return ;
	}
	m_bRunThread = TRUE;
}
int CServerDlg::InitDataProc()
{
//  RTPSession m_rtpSession;

  int status;
 
  // 获得接收端的IP地址和端口号
 	unsigned long localIP = inet_addr(LOCAL_IP);
		_ASSERT(localIP != INADDR_NONE);
  // 创建RTP会话
  status = m_rtpSession.Create(SERVER_PORT,localIP);
 // checkerror(status);
  if(!status)
	  return 0;
//  MessageBox("error1");
	unsigned long intIP = inet_addr(MCAST_IP);
	_ASSERT(intIP != INADDR_NONE);
	intIP = ntohl(intIP); //put in host byt
  // 指定RTP数据接收端
  status = m_rtpSession.AddDestination(intIP, MCAST_PORT);
	  if(!status)
	  return 0;

  // 设置RTP会话默认参数
  m_rtpSession.SetDefaultPayloadType(0);
  m_rtpSession.SetDefaultMark(false);
  m_rtpSession.SetDefaultTimeStampIncrement(10);

  // 发送流媒体数据
 char testBuf[MAX_PACKET_SIZE];
 /*
 while(m_llMediaLen)
 {	
	//SEND a packet
			LONGLONG byteCnt = rand() % sizeof(testBuf);
			m_rtpSession.SendPacket(testBuf, byteCnt);
			LONGLONG m_llMediaLen=m_llMediaLen-byteCnt;

  }*/

  return 1;
}
/*
DWORD WINAPI CServerDlg::PollDataProc(void *pParam)
{
//	RTPSession rtpSession;
	//setup session parameters
	RTPSessionParams sessParams;
	sessParams.SetOwnTimestampUnit(1.0 / 30.0); //30 video frames per second
	sessParams.SetUsePollThread(1); //background thread to call virtual callbacks - set by default, but just to be sure
	sessParams.SetMaximumPacketSize(MAX_PACKET_SIZE);
	//setup transmission parameters
	RTPUDPv4TransmissionParams transParams;
	transParams.SetPortbase(SERVER_PORT);
	//CREATE THE SESSION
	int status = m_rtpSession.Create(sessParams, &transParams);
	if (ReportError(status))
		return; //unable to create the session
	printf("RTP session created with portbase %d\n", SERVER_PORT);

	//SET TRANSMISSION DEFAULTS if we want to use them
	//rtpSession.SetDefaultPayloadType(96);
	//rtpSession.SetDefaultMark(false);
	//rtpSession.SetDefaultTimestampIncrement(160);

	//ADD THE MULTICAST to our destination
	unsigned long intIP = inet_addr(MCAST_IP);
	_ASSERT(intIP != INADDR_NONE);
	intIP = ntohl(intIP); //put in host byte order
	RTPIPv4Address rtpAddr(intIP, MCAST_PORT);
	status = m_rtpSession.AddDestination(rtpAddr);
	if (!ReportError(status)) {
		printf("Transmitting to multicast group %s port %d\n\n", MCAST_IP, MCAST_PORT);
		MessageBox("add");
		char testBuf[MAX_PACKET_SIZE];
		while (1) {
		//	printf("\n_______________________________________________________\nPress Enter key to send data - 'x' to exit\n");
		//	int ch = getchar();
		//	if (tolower(ch) == 'x')
				break;
			//SEND a packet
			int byteCnt = rand() % sizeof(testBuf);
			m_rtpSession.SendPacket(testBuf, byteCnt, 0, false, 10UL);
			printf("%d bytes sent\n", byteCnt);
		}

		//LEAVE THE MULTICAST
		m_rtpSession.DeleteDestination(rtpAddr);
	}
	m_rtpSession.Destroy();
}
*/

DWORD WINAPI CServerDlg::PollDataProc(void *pParam)
{


	CServerDlg *pDlg = (CServerDlg*)pParam;
	int nRet = 0;
//	m_llMediaLen
	while(1)
	{
		nRet = pDlg->m_rtpSession.PollData();

		if (pDlg->m_rtpSession.GotoFirstSourceWithData())
		{
			do

			{
				RTPPacket *pack;
				
				pack = pDlg->m_rtpSession.GetNextPacket();
				pDlg->ProcessQuery((char*)pack->GetPayload(),
						pack->GetPayloadLength());
				delete pack;				
			} while (pDlg->m_rtpSession.GotoNextSourceWithData());
		}
		Sleep(1);
	}
	return 1;
}

BOOL CServerDlg::ProcessQuery(char *pbData,int nLength)
{
	CTRLMSG msg;
	LPBYTE lpBuffer = NULL;
	memcpy(&msg,pbData,sizeof(CTRLMSG));
	DWORD dwGotSize;
	DWORD dwBytesHaveSend = 0;
	DWORD dwBytesToSend = msg.dwBytesToRead;
	switch(msg.msgType) {
	case QUEST_DATA:
		CURRENCY llThePos;
		llThePos.int64= msg.lPos;
		SetFilePointer(m_hMediaFile,llThePos.Lo,&llThePos.Hi,FILE_BEGIN);
		while(dwBytesHaveSend <dwBytesToSend) {
			msg.msgType = REPLY_DATA;
			msg.msgSubType = OTHER;
			msg.lPos = 0;
			msg.dwLength = dwBytesToSend-dwBytesHaveSend > 8192 ? 8192:dwBytesToSend-dwBytesHaveSend;
			lpBuffer = new BYTE[(int)msg.dwLength+sizeof(CTRLMSG)];
			ReadFile(m_hMediaFile,lpBuffer+sizeof(CTRLMSG),msg.dwLength,&dwGotSize,NULL);
			memcpy(lpBuffer,&msg,sizeof(CTRLMSG));
			m_rtpSession.SendPacket(lpBuffer,
				msg.dwLength + sizeof(CTRLMSG));
			Sleep(10);
			delete lpBuffer;
			dwBytesHaveSend += msg.dwLength ;
			//TRACE("Send %d Bytes\n",msg.dwLength);
		}
		break;
	case QUEST_LENGTH:
		//SetMediaLength(m_msg.lPos);
		msg.msgType = REPLY_LENGTH;
		msg.msgSubType = OTHER;
		msg.lPos = m_llMediaLen;
		msg.dwLength = 0;
		m_rtpSession.SendPacket(&msg,sizeof(CTRLMSG));
		break;
	};
	return TRUE;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -