Socket通信实例

1.通信协议:

#ifndef _PROTOCOL_H__
#define _PROTOCOL_H__

namespace OurTutorial
{
    
	struct Protocol
	{
		int		iCmd;				//type 0-文件开始 1-文件数据 2-文件结束
		char	buff[100];
		int		iUsedSize;			//z
	};
}

#endif


2.Client端

// SocketClient_VSDlg.cpp : implementation file
//

#include "stdafx.h"
#include "SocketClient_VS.h"
#include "SocketClient_VSDlg.h"
#include<vector>
#include <fstream>
using namespace std;

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

#include <WinSock.h>

#include "rotocol.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg:oDataExchange(CDataExchange* pDX)
{
	CDialog:oDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CSocketClient_VSDlg dialog




CSocketClient_VSDlg::CSocketClient_VSDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSocketClient_VSDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CSocketClient_VSDlg:oDataExchange(CDataExchange* pDX)
{
	CDialog:oDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CSocketClient_VSDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_TIMER()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON1, &CSocketClient_VSDlg::OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, &CSocketClient_VSDlg::OnBnClickedButton2)
	ON_BN_CLICKED(IDC_BUTTON3, &CSocketClient_VSDlg::OnBnClickedButton3)
END_MESSAGE_MAP()


// CSocketClient_VSDlg message handlers

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

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 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

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CSocketClient_VSDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// 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 CSocketClient_VSDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<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 function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CSocketClient_VSDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CSocketClient_VSDlg::OnBnClickedButton1()
{
	CString FilePathName; 
	CFileDialog dlg(TRUE);///TRUE为OPEN对话框,FALSE为SAVE AS对话框 
	if(dlg.DoModal()==IDOK) 
		FilePathName=dlg.GetPathName(); 


	mFileName = FilePathName;

	// TODO: Add your control notification handler code here
}

void CSocketClient_VSDlg::OnBnClickedButton2()
{
	FILE* fp = fopen( mFileName.c_str(),"rb" );
	if ( fp )
	{
		OurTutorial:rotocol stProtocol;
		stProtocol.iCmd = 0;
		send( mSocketFD, (char*)(&stProtocol), sizeof(stProtocol), 0 );

		int iTotalSize = 0;
		while( !feof(fp))
		{
			int iSize = 0;
			int iNum = 0;
			if ( iNum != SOCKET_ERROR )
			{
				iSize = fread( stProtocol.buff, 1, 100, fp );
			}
			else
			{
				Sleep( 200 );
			}
				

			stProtocol.iCmd = 1;
			stProtocol.iUsedSize = iSize;

			iNum = send( mSocketFD, (char*)(&stProtocol), sizeof(stProtocol), 0 );

			iTotalSize += iSize;
		}

		stProtocol.iCmd = 2;

		send( mSocketFD, (char*)(&stProtocol), sizeof(stProtocol), 0 );
		fclose( fp );
	}
	// TODO: Add your control notification handler code here
}

void CSocketClient_VSDlg::OnBnClickedButton3()
{
	// TODO: Add your control notification handler code here
	WORD wVersionReq = MAKEWORD( 2, 2 );
	WSADATA wsaData;
	int err = 0;

	err = WSAStartup( wVersionReq, &wsaData );
	if ( err != 0 )
	{
		printf( "WSAStartup Failed \n");
		WSACleanup();
		return;
	}  
	mSocketFD = socket( AF_INET, SOCK_STREAM, 0 );

	if ( mSocketFD == SOCKET_ERROR )
	{
		printf( "Create Socket Failed!\n");
		return;
	}

	hostent* hostEnty = gethostbyname( "127.0.0.1" );
	if ( hostEnty == 0 )
	{
		return;

	}
	sockaddr_in s_addrData;
	memset( &s_addrData, 0, sizeof( s_addrData) );
	s_addrData.sin_addr.s_addr = ( (in_addr*)(hostEnty->h_addr) )->s_addr;
	s_addrData.sin_family = AF_INET;
	s_addrData.sin_port = htons( 44965 );
	int iRet = connect( mSocketFD, (struct sockaddr*)&s_addrData,sizeof( struct sockaddr) );
	if ( iRet == SOCKET_ERROR )
	{
		printf( "Can't Connect Server! \n");
		getchar();
		return;
	}
}

void CSocketClient_VSDlg::OnTimer( UINT_PTR nIDEvent )
{

	//TODO:
}
3.Server端:
// SocketServer_VSDlg.cpp : implementation file//#include "stdafx.h"#include "SocketServer_VS.h"#include "SocketServer_VSDlg.h"#include <Windows.h>#include <iostream>#include <vector>using namespace std;#include <fstream>#define NO_FLAGS_SET 0#define PORT (u_short)44965 #define MAXBUFLEN 256#include "rotocol.h"#ifdef _DEBUG#define new DEBUG_NEW#endif// CAboutDlg dialog used for App Aboutclass CAboutDlg : public CDialog{public:CAboutDlg();// Dialog Dataenum { IDD = IDD_ABOUTBOX };protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support// Implementationprotected:DECLARE_MESSAGE_MAP()};CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){}void CAboutDlg:oDataExchange(CDataExchange* pDX){CDialog:oDataExchange(pDX);}BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)END_MESSAGE_MAP()// CSocketServer_VSDlg dialogCSocketServer_VSDlg::CSocketServer_VSDlg(CWnd* pParent /*=NULL*/): CDialog(CSocketServer_VSDlg::IDD, pParent){m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);}void CSocketServer_VSDlg:oDataExchange(CDataExchange* pDX){CDialog:oDataExchange(pDX);}BEGIN_MESSAGE_MAP(CSocketServer_VSDlg, CDialog)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()//}}AFX_MSG_MAPON_BN_CLICKED(IDC_BUTTON1, &CSocketServer_VSDlg::OnBnClickedButton1)ON_BN_CLICKED(IDC_BUTTON2, &CSocketServer_VSDlg::OnBnClickedButton2)ON_BN_CLICKED(IDC_BUTTON3, &CSocketServer_VSDlg::OnBnClickedButton3)END_MESSAGE_MAP()// CSocketServer_VSDlg message handlersBOOL CSocketServer_VSDlg::OnInitDialog(){CDialog::OnInitDialog();// Add "About..." menu item to system menu.// IDM_ABOUTBOX must be in the system command range.ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){pSysMenu->AppendMenu(MF_SEPARATOR);pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);}}// Set the icon for this dialog. The framework does this automatically// when the application's main window is not a dialogSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small icon// TODO: Add extra initialization herereturn TRUE; // return TRUE unless you set the focus to a control}void CSocketServer_VSDlg::OnSysCommand(UINT nID, LPARAM lParam){if ((nID & 0xFFF0) == IDM_ABOUTBOX){CAboutDlg dlgAbout;dlgAbout.DoModal();}else{CDialog::OnSysCommand(nID, lParam);}}// 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 CSocketServer_VSDlg::OnPaint(){if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);// Center icon in client rectangleint 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 icondc.DrawIcon(x, y, m_hIcon);}else{CDialog::OnPaint();}}// The system calls this function to obtain the cursor to display while the user drags// the minimized window.HCURSOR CSocketServer_VSDlg::OnQueryDragIcon(){return static_cast<HCURSOR>(m_hIcon);}vector<char> data;void CSocketServer_VSDlg::OnBnClickedButton1(){WSADATA Data;SOCKADDR_IN serverSockAddr;SOCKADDR_IN clientSockAddr;SOCKET severSocket;int addrLen = sizeof(SOCKADDR_IN);char buffer[MAXBUFLEN];status = WSAStartup(MAKEWORD(1,1), &Data);if (status != 0){printf( "ERROR: WSASartup unsuccessful");}memset( &serverSockAddr,0, sizeof(serverSockAddr));serverSockAddr.sin_port = htons(PORT);serverSockAddr.sin_family = AF_INET;serverSockAddr.sin_addr.s_addr = htonl(INADDR_ANY);severSocket = socket(AF_INET, SOCK_STREAM, 0);if ( severSocket == INVALID_SOCKET ){printf( "Error: socket unsuccessful");}status = bind( severSocket, (LPSOCKADDR)&serverSockAddr,sizeof(serverSockAddr) );if ( status == SOCKET_ERROR ){printf( "Error: bind unsuccessful ");}status = listen( severSocket, 1 );if ( status == SOCKET_ERROR ){printf( "ERROR: listen unsuccessful \n");}mClientSocket = accept( severSocket,(LPSOCKADDR)&clientSockAddr, &addrLen );// TODO: Add your control notification handler code here}void CSocketServer_VSDlg::OnBnClickedButton2(){CString FilePathName; CFileDialog dlg(FALSE);///TRUE为OPEN对话框,FALSE为SAVE AS对话框 if(dlg.DoModal()==IDOK) FilePathName=dlg.GetPathName(); mFileName = FilePathName;// TODO: Add your control notification handler code here}void CSocketServer_VSDlg::OnBnClickedButton3(){FILE* fp2 = NULL;char buffer[1000];int iProtocolSize = sizeof( OurTutorial:rotocol );while ( 1 ){numrcv = recv( mClientSocket, buffer, 108, NO_FLAGS_SET );if ( numrcv == iProtocolSize ){OurTutorial:rotocol* pProtocolData = (OurTutorial:rotocol*)buffer;if ( pProtocolData->iCmd == 0 ){fp2 = fopen( mFileName.c_str(), "wb");}else if ( pProtocolData->iCmd == 1 ){fwrite( pProtocolData->buff, 1, pProtocolData->iUsedSize, fp2 );}else if( pProtocolData->iCmd == 2 ){fclose( fp2 );break;}}}return;// FILE* fp = fopen( mFileName.c_str(), "wb");// if ( fp )// {// char buffer[100];// int iTotalSize = 0;// do{// numrcv = recv( mClientSocket, buffer, 100, NO_FLAGS_SET );// if ( numrcv > 0 )// {// iTotalSize += numrcv;// int iSize = fwrite( buffer, 1, 100, fp );// }// if ((numrcv == 0)||( numrcv == SOCKET_ERROR))// {// printf( "Connection terminated.\n");// status = closesocket(mClientSocket);// if ( status == SOCKET_ERROR)// {// printf( "ERROR: closesocket unsuccessful\n"); }// status = WSACleanup();// if ( status == SOCKET_ERROR )// {// printf("ERROR: WSACleanup unsuccessful\n"); } }// res = send( mClientSocket,buffer,numrcv,0 ); if ( res == -1 ) { printf( "Send Failed!\n"); } }while( numrcv != 0 && numrcv != -1 ); fclose(fp);/* }*/// TODO: Add your control notification handler code here}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值