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

📄 chatdlg.cpp

📁 tcp、winsock编程
💻 CPP
字号:
// chatDlg.cpp : implementation file
//

#include "stdafx.h"
#include "chat.h"
#include "chatDlg.h"
#include "InitDlg.h"

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

volatile int threadController;
char * name;
char * IP;
int PORT;
CInitDlg BeginDlg;
/////////////////////////////////////////////////////////////////////////////
// CChatDlg dialog

CChatDlg::CChatDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CChatDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CChatDlg)
	m_send = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CChatDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CChatDlg)
	DDX_Control(pDX, IDC_BUTTON1, m_stoprecv);
	DDX_Control(pDX, IDC_LIST1, m_recv);
	DDX_Text(pDX, IDC_EDIT1, m_send);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CChatDlg, CDialog)
	//{{AFX_MSG_MAP(CChatDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1, OnRecv)
	ON_BN_CLICKED(IDC_BUTTON2, OnStopRecv)
	ON_BN_CLICKED(IDOK, OnSend)
	//}}AFX_MSG_MAP
	ON_MESSAGE(WM_RECIEVED, OnRecieved)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChatDlg message handlers

BOOL CChatDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	
	BeginDlg.DoModal();
	name = new char[256];
	IP = new char[16];
	strcpy(IP,"192.168.0.62");
	PORT = 1024;
	// 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
}

// 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 CChatDlg::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 CChatDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

HANDLE RecvProc(LPVOID param)
{
	WORD wVersionRequested;
	WSAData  wsaData;
	struct sockaddr_in client;
	struct sockaddr_in server;
	char buf[256];
	int s;
	int clientfd;
	int err; 

	//start socket
	wVersionRequested = MAKEWORD( 2, 0 ); 
	err = WSAStartup( wVersionRequested, &wsaData );
	if ( err != 0 ) return 0;
	if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 0 ) {
		WSACleanup( );
		return 0; 
	}	

	//create socket
	if ((s=socket(AF_INET, SOCK_STREAM,0))<0){
		return 0;
	}

	//bind socket
	server.sin_family = AF_INET;
	PORT = atoi(BeginDlg.m_port);
	server.sin_port = htons(PORT);
	server.sin_addr.s_addr = INADDR_ANY;
	if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR){
		return 0;
	}

	int length = sizeof(server);
	if(getsockname(s,(struct sockaddr *)&server,&length) < 0){
		return 0;
	}

	if(listen(s,1)!=0){
		return 0;
    }

	int tmp=sizeof(server);
	int flag=0;
	int clientnamelen=sizeof(client);
	int pktlentmp;
	CString tmpstr1;
	while(threadController){
	if((clientfd=accept(s,(struct sockaddr *)&client,&clientnamelen))==-1){
		return 0;
        }

		if ((pktlentmp = recv(clientfd,buf,256,0))<=0){
		return 0;
			break;
		}
		else{
			strcpy(name,buf);
			::PostMessage((HWND)param, WM_RECIEVED, 0, 0);
		}
	}
	closesocket(clientfd);
	closesocket(s);

	WSACleanup( );
    ::MessageBox((HWND)param, "接收已经停止!", "注意", MB_OK);    
	return 0;
}

void CChatDlg::OnRecv() 
{
	HWND hWnd = GetSafeHwnd();
	threadController = 1;
	AfxBeginThread((AFX_THREADPROC)RecvProc, hWnd, THREAD_PRIORITY_NORMAL);
	GetDlgItem(IDC_BUTTON2)->EnableWindow(true);
}

void CChatDlg::OnStopRecv() 
{
	threadController = 0;
	GetDlgItem(IDC_BUTTON1)->EnableWindow(false);
	GetDlgItem(IDOK)->EnableWindow(false);
}


void CChatDlg::OnSend() 
{
	//Use Socket to Send The UserName and ComputerName
	WORD wVersionRequested;
	WSAData  wsaData;
	struct hostent *hp;
	struct sockaddr_in client;
	unsigned long ip_addr;
	int sendlen;
	int s;
	int err; 
	wVersionRequested = MAKEWORD( 2, 0 ); 
	err = WSAStartup( wVersionRequested, &wsaData );
	if ( err != 0 ) { 
		ErrorMessage("Socket0.0版本错误");
		return;
	}
	if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 0 ) {
		ErrorMessage("Socket1.0版本错误");
		WSACleanup( );
		return; 
	}	

	strcpy(IP,BeginDlg.m_ip);
	PORT = atoi(BeginDlg.m_port);
//	strcpy(tmpport,BeginDlg.m_port);
    ip_addr=inet_addr(IP);
    hp=gethostbyaddr((char *)&ip_addr,4,PF_INET);
    if(hp==NULL){
		ErrorMessage("获取IP地址信息错误");
		return;
    }
	
	memcpy(&client.sin_addr,hp->h_addr,hp->h_length);
	if((s=socket(AF_INET,SOCK_STREAM,0))<0){
		ErrorMessage("创建Socket错误");
		return;
	}
	client.sin_family=AF_INET;
	client.sin_port=htons(PORT);
	if(connect(s,(struct sockaddr*)&client,sizeof(client))<0){
		closesocket(s);
		ErrorMessage("Socket连接错误");
		return;
	}
	UpdateData(true);
	if((sendlen=send(s,m_send,256,0))<=0){
		ErrorMessage("Socket发送错误");
		return;
	}

	WSACleanup( );
//	AfxMessageBox("发送完成!",MB_OK,0);
	return;
	
}




LONG CChatDlg::OnRecieved(WPARAM wParam, LPARAM lParam)
{
	m_recv.AddString(_T(name));
	UpdateData(false);
    return 0;
}

void CChatDlg::ErrorMessage(CString Msg) 
{
	LPVOID lpMsgBuf;
	FormatMessage( 
		FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
		NULL,
		GetLastError(),
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		(LPTSTR) &lpMsgBuf,
		0,
		NULL 
		);
	MessageBox((LPCTSTR )lpMsgBuf, Msg, MB_OK);
	LocalFree( lpMsgBuf );
	WSACleanup( );
}

⌨️ 快捷键说明

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