📄 tcptalkdlg.cpp
字号:
// TCPTalkDlg.cpp : implementation file
//
#include "stdafx.h"
#include "TCPTalk.h"
#include "TCPTalkDlg.h"
#define INDICATOR 2
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
//和通信线城相关的全局变量
CWinThread *pThreadSendMsg; //发送消息线程
CWinThread *pThreadLisen; //监听线程-->_ListenTcpThread
//TCP监听线程
UINT _ListenTcpThread(LPVOID lparam)
{
CTCPTalkDlg *pDlg=(CTCPTalkDlg *)lparam;
CSocket sockSrvr;
int createSucceed=sockSrvr.Create(pDlg->m_nPortLocal);
if(createSucceed==0)
{
AfxMessageBox("建立Socket错误!");
return -1;
}
//开始监听
int listenSucceed=sockSrvr.Listen();
if(listenSucceed==0)
{
AfxMessageBox("监听错误!");
return -1;
}
CSocket recSo;
SOCKADDR_IN client;
int iAddrSize=sizeof(client);
//接受连接并取得对方IP
int acceptSucceed=sockSrvr.Accept(recSo,(SOCKADDR *)&client,&iAddrSize);
if(acceptSucceed==0)
{
AfxMessageBox("接收错误!");
return -1;
}
sockSrvr.Close();
char Indicator[INDICATOR]={0};
if(recSo.Receive(Indicator,INDICATOR)!=2)
{
return -1;
}
pDlg->m_datatype=Indicator[0];
if(pDlg->m_datatype=='D')
{
return 0;
}
pThreadLisen=::AfxBeginThread(_ListenTcpThread,pDlg);
pDlg->ProcessReceivedMessage(recSo,client);
return 0;
}
//TCP发送信息线程
UINT _SendMsgThread(LPVOID lparam)
{
CTCPTalkDlg *pDlg=(CTCPTalkDlg *)lparam;
CSocket sockClient;
sockClient.Create();
CString ip,strError;
pDlg->m_CtrlRemoteIP.GetWindowText(ip);
int conn=sockClient.Connect(ip,pDlg->m_nPortRemote);
if(conn==0)
{
AfxMessageBox("建立连接错误!");
sockClient.ShutDown(2);
sockClient.Close();
AfxEndThread(1L);
return 0;
}
//首先发送标记M为信息,2
int end=0;
end=sockClient.Send("M",INDICATOR);
if(end==SOCKET_ERROR)
{
AfxMessageBox("发送标记错误!");
return -1;
}
else if(end!=2)
{
AfxMessageBox("消息头错误");
return -1;
}
CString strMsg=pDlg->m_strSend;
end=sockClient.Send(strMsg,strMsg.GetLength());
if(end==SOCKET_ERROR)
{
AfxMessageBox("发送消息错误!");
return -1;
}
int i=0;
sockClient.Close();
return 0;
}
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTCPTalkDlg dialog
CTCPTalkDlg::CTCPTalkDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTCPTalkDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CTCPTalkDlg)
m_nPortLocal = 0;
m_nPortRemote = 0;
m_strMessage = _T("");
m_strSend = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CTCPTalkDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTCPTalkDlg)
DDX_Control(pDX, IDC_EDIT_MESSAGE, m_CtrlMessage);
DDX_Control(pDX, IDC_IPADDRESS_REMOTE, m_CtrlRemoteIP);
DDX_Control(pDX, IDC_IPADDRESS_LOCAL, m_CtrlLocalIP);
DDX_Text(pDX, IDC_EDIT_PORT_LOCAL, m_nPortLocal);
DDV_MinMaxInt(pDX, m_nPortLocal, 0, 65535);
DDX_Text(pDX, IDC_EDIT_PORT_REMOTE, m_nPortRemote);
DDV_MinMaxInt(pDX, m_nPortRemote, 0, 65535);
DDX_Text(pDX, IDC_EDIT_MESSAGE, m_strMessage);
DDX_Text(pDX, IDC_EDIT_SEND, m_strSend);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CTCPTalkDlg, CDialog)
//{{AFX_MSG_MAP(CTCPTalkDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_LISTEN, OnListen)
ON_BN_CLICKED(IDC_SEND_MESSAGE, OnSendMessage)
ON_BN_CLICKED(IDC_CLEAR_MESSAGE, OnClearMessage)
ON_WM_DESTROY()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTCPTalkDlg message handlers
BOOL CTCPTalkDlg::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
//1.设置默认端口值
m_nPortLocal=13400;
m_nPortRemote=13400;
//2.获取本机计算机名称
GetLocalHostName(m_strLocalName);
//3.获取本机IP
GetIpAddress(m_strLocalName,m_strLocalIP);
m_CtrlLocalIP.SetWindowText(m_strLocalIP);
//4.默认的对方IP和本机相同
m_strRemoteIP=m_strLocalIP;
m_CtrlRemoteIP.SetWindowText(m_strRemoteIP);
//5.默认为不接收
Receive=FALSE;
Busy=FALSE;
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
}
void CTCPTalkDlg::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 CTCPTalkDlg::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 CTCPTalkDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
int CTCPTalkDlg::GetLocalHostName(CString &sLocalName) //获得本地计算机名称
{
char szLocalName[256];
int nRetCode;
nRetCode=gethostname(szLocalName,sizeof(szLocalName));
if(nRetCode!=0)
{
//产生错误
sLocalName=_T("没有取得");
return GetLastError();
}
sLocalName=szLocalName;
return 0;
}
int CTCPTalkDlg::GetIpAddress(const CString &sLocalName, CString &sIpAddress)//获得本地IP
{
struct hostent FAR * lpHostEnt=gethostbyname(sLocalName);
if(lpHostEnt==NULL)
{
//产生错误
sIpAddress=_T("");
return GetLastError();
}
//获取IP
LPSTR lpAddr=lpHostEnt->h_addr_list[0];
if(lpAddr)
{
struct in_addr inAddr;
memmove(&inAddr,lpAddr,4);
//转换为标准格式
sIpAddress=inet_ntoa(inAddr);
if(sIpAddress.IsEmpty())
{
sIpAddress=_T("没有取得");
}
}
return 0;
}
int CTCPTalkDlg::GetNamebyAddress(const CString &IpAddress,CString &sRemoteName)//获得对方计算机名称
{
unsigned long addr;
addr=inet_addr(IpAddress);
struct hostent FAR * lpHostEnt=gethostbyaddr((char *)&addr,4,AF_INET);
if(lpHostEnt==NULL)
{
//产生错误
sRemoteName=_T("");
AfxMessageBox("连接不上");
return -1;
}
CString name=lpHostEnt->h_name;
sRemoteName=name;
return 0;
}
int CTCPTalkDlg::ProcessReceivedMessage(CSocket &recSo,SOCKADDR_IN &client) //处理收到消息的函数
{
if(m_datatype=='M') //文本信息
{
char buff[1024]={0};
CString msg;
int ret=0;
for(;;)
{
ret=recSo.Receive(buff,1024);
if(ret==0)
break;
msg+=buff;
}
//更新显示
CString MessageRemoteName;
GetNamebyAddress(m_strRemoteIP,MessageRemoteName);
m_strMessage+=MessageRemoteName+":"+"\r\n"+msg+"\r\n"+"\r\n";
SetDlgItemText(IDC_EDIT_MESSAGE,m_strMessage);
m_CtrlMessage.SetSel(m_strMessage.GetLength(),m_strMessage.GetLength(),FALSE);
}
recSo.Close();
return 0;
}
void CTCPTalkDlg::OnListen()
{
m_nPortRemote=GetDlgItemInt(IDC_EDIT_PORT_REMOTE,NULL,TRUE);
m_nPortLocal=GetDlgItemInt(IDC_EDIT_PORT_LOCAL,NULL,TRUE);
m_CtrlRemoteIP.GetWindowText(m_strRemoteIP);
GetDlgItemText(IDC_EDIT_SEND,m_strSend);
UpdateData(false);
if(!Receive)
{
//开始监听
pThreadLisen=::AfxBeginThread(_ListenTcpThread,this);
Receive=TRUE;
SetDlgItemText(IDC_LISTEN,"不接收");
}
else
{
//停止监听
Receive=FALSE;
SetDlgItemText(IDC_LISTEN,"接收");
DWORD dwStatus;
if (pThreadLisen != NULL)
{
if(::GetExitCodeThread(pThreadLisen->m_hThread, &dwStatus)==0)
{
int errror=GetLastError();
return;
}
if (dwStatus == STILL_ACTIVE)
{
CSocket sockClient;
sockClient.Create();
CString ip,strError;
ip="127.0.0.1";
int conn=sockClient.Connect(ip, m_nPortLocal);
if(conn==0) ///////////////////////////////////
{
AfxMessageBox("关闭错误!");
sockClient.ShutDown(2);
sockClient.Close();
return;
}
sockClient.Send("D",INDICATOR); //结束
}
else
{
delete pThreadLisen;
pThreadLisen = NULL;
}
}
}
}
void CTCPTalkDlg::OnSendMessage()
{
m_nPortRemote=GetDlgItemInt(IDC_EDIT_PORT_REMOTE,NULL,TRUE);
GetDlgItemText(IDC_EDIT_SEND,m_strSend);
m_CtrlRemoteIP.GetWindowText(m_strRemoteIP);
UpdateData(false);
if(m_strSend.GetLength()==0)
{
return;
}
::AfxBeginThread(_SendMsgThread,this);
//更新显示
m_strMessage+=m_strLocalName+":"+"\r\n"+m_strSend+"\r\n"+"\r\n";
SetDlgItemText(IDC_EDIT_MESSAGE,m_strMessage);
m_CtrlMessage.SetSel(m_strMessage.GetLength(),m_strMessage.GetLength(),FALSE);
}
void CTCPTalkDlg::OnClearMessage()
{
GetDlgItemText(IDC_EDIT_SEND,m_strSend);
m_strMessage.Empty();
UpdateData(false);
}
void CTCPTalkDlg::OnDestroy()
{
CDialog::OnDestroy();
if(Receive)
{
//停止监听
DWORD dwStatus;
if (pThreadLisen != NULL)
{
if(::GetExitCodeThread(pThreadLisen->m_hThread, &dwStatus)==0)
{
int errror=GetLastError();
return;
}
if (dwStatus == STILL_ACTIVE)
{
CSocket sockClient;
sockClient.Create();
CString ip,strError;
ip="127.0.0.1";
int conn=sockClient.Connect(ip, m_nPortLocal);
if(conn==0) ///////////////////////////////////
{
AfxMessageBox("关闭错误!");
sockClient.ShutDown(2);
sockClient.Close();
return;
}
sockClient.Send("D",INDICATOR); //结束
}
else
{
delete pThreadLisen;
pThreadLisen = NULL;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -