Socket編程在大多數(shù)的編程語言中都是一件比較有趣的事情。它是比較常用的編寫通過網(wǎng)絡(luò)通信的服務(wù)器和客戶端方法。在windows平臺(tái)Socket通信大多是基于MS Winsock設(shè)計(jì)的。Windows支持基于TCP和UDP的socket通信。Windows APIs在socket編程中是非常有用的,但是有些人發(fā)現(xiàn)在用它們工作的時(shí)候有困難。
所以在這里我介紹一種最簡單用MFC socket類進(jìn)行socket編程的方法。這不僅可以使你的工作變得簡單而且能減少你在網(wǎng)絡(luò)程序上的開發(fā)時(shí)間。你可以定制一個(gè)socket類,然后你可以在你的其他的網(wǎng)絡(luò)應(yīng)用程序中重用。
在socket編程中,MFC提供了兩個(gè)基本的類,分別是CAsyncSocket和Csocket。Csocket是從CAsyncSocket繼承來的。我們可以建立定制的socket類,也是從CasyncSocket繼承而來的,當(dāng)然也是為了我們程序特殊的需要。
初始化socket
首先需要調(diào)用AfxSocketInit()函數(shù)來初始化我們的socket環(huán)境。
為了初始化sockets,我們需要調(diào)用AfxSocketInit()函數(shù)。它通常是在MFC中的InitInstance()函數(shù)中被調(diào)用的。如果我們用程序向?qū)韯?chuàng)建socket程序的話,查看“use Windows Sockets”這個(gè)選項(xiàng),然后選中它。它將會(huì)自動(dòng)的為我們創(chuàng)建這個(gè)步驟了。(如果我們沒有選中這個(gè)選項(xiàng)的話,我們也可以手動(dòng)添加這些代碼的。)這個(gè)函數(shù)的返回值顯示這個(gè)函數(shù)的調(diào)用成功或失敗。
BOOL CServerApp::InitInstance()
{....
if( AfxSocketInit() == FALSE)
{
AfxMessageBox("Sockets Could Not Be Initialized");
return FALSE;
}
...
}
創(chuàng)建Server Sockets
為了創(chuàng)建一個(gè)Server Socket,我們需要聲明一個(gè)CAyncSocket的變量或者我們自己定制的一個(gè)從AyncSocket或是Cscket繼承來的類的類型的變量。然后調(diào)用Create()函數(shù),同時(shí)指定監(jiān)聽的端口。這個(gè)函數(shù)的返回值顯示這個(gè)函數(shù)的調(diào)用成功或失敗。
UpdateData(TRUE);
m_sListener.Create(m_port);
if(m_sListener.Listen()==FALSE)
{
AfxMessageBox("Unable to Listen on that port,please try another port");
m_sListener.Close();
return;
}
創(chuàng)建Client Sockets
為了創(chuàng)建Client socket類,我們需要聲明一個(gè)CAyncSocket的變量或者我們自己定制的一個(gè)從AyncSocket或是Cscket繼承來的類的類型的變量。然后調(diào)用Create()函數(shù),同時(shí)指定監(jiān)聽的端口。這個(gè)函數(shù)的返回值顯示這個(gè)函數(shù)的調(diào)用成功或失敗。
m_sConnected.Create();
m_sConnected.Connect("server ip",port);
監(jiān)聽客戶端的連接
創(chuàng)建了server socket以后,我們要進(jìn)行監(jiān)聽。調(diào)用Listen()函數(shù)。這個(gè)函數(shù)的返回值顯示這個(gè)函數(shù)的調(diào)用成功或失敗。
if( m_sListener.Listen()== FALSE)
{
AfxMessageBox("Unable to Listen on that port,please try another port");
m_sListener.Close();
return;
}
接受連接
連接請求要被接受accept,是用另外的socket,不是正在監(jiān)聽的socket。請參看代碼。
void CXXXDlg::OnAccept()
{
CString strIP;
UINT port;
if(m_sListener.Accept(m_sConnected))
{
m_sConnected.GetSockName(strIP,port); //應(yīng)該是GetPeerName,獲取對(duì)方的IP和port
m_status="Client Connected,IP :"+ strIP;
m_sConnected.Send("Connected To Server",strlen("Connected To Server"));
UpdateData(FALSE);
}
else
{
AfxMessageBox("Cannoot Accept Connection");
}
}
發(fā)送數(shù)據(jù)
數(shù)據(jù)放在一個(gè)buffer中或是結(jié)構(gòu)體中,調(diào)用send()函數(shù)發(fā)送。
m_sConnected.Send(pBuf,iLen);
接受數(shù)據(jù)
調(diào)用receive()接受數(shù)據(jù)。
void CXXXrDlg::OnReceive()
{
char *pBuf =new char [1025];
CString strData;
int iLen;
iLen=m_sConnected.Receive(pBuf,1024);
if(iLen == SOCKET_ERROR)
{
AfxMessageBox("Could not Recieve");
}
else
{
pBuf[iLen]=NULL;
strData=pBuf;
m_recieveddata.Insert(m_recieveddata.GetLength(),strData);
//display in server
UpdateData(FALSE);
m_sConnected.Send(pBuf,iLen); //send the data back to the Client
delete pBuf;
}
}
關(guān)閉連接
m_sConnected.ShutDown(0); 停止發(fā)送數(shù)據(jù)
m_sConnected.ShutDown(1); 停止接受數(shù)據(jù)
m_sConnected.ShutDown(2); 停止發(fā)送接受數(shù)據(jù)
m_sConnected.Close();
編寫自己的socket類
在class view中選擇添加一個(gè)新類,設(shè)置它的基類為CAsyncSocket,在類向?qū)У膸椭绿砑尤缦碌囊恍┖瘮?shù)。
class MySocket : public CAsyncSocket
{ // Attributes
public:
// Operations
public:
MySocket();
virtual ~MySocket();
// Overrides
public:
void SetParentDlg(CDialog *pDlg);// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(MySocket)
public:
virtual void OnAccept(int nErrorCode);
virtual void OnClose(int nErrorCode);
virtual void OnConnect(int nErrorCode);
virtual void OnOutOfBandData(int nErrorCode);
virtual void OnReceive(int nErrorCode);
virtual void OnSend(int nErrorCode);
//}}AFX_VIRTUAL // Generated message map functions
//{{AFX_MSG(MySocket)
// NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG
protected:
private:
CDialog * m_pDlg;
};
設(shè)置“Parent Dialog”
調(diào)用這個(gè)socket類的SetParentDlg函數(shù),保證當(dāng)socket事件發(fā)生的時(shí)候這個(gè)窗體能接收到。
m_sListener.SetParentDlg(this);
m_sConnected.SetParentDlg(this);
建立Socket 事件和窗體成員函數(shù)之間的聯(lián)系
在這個(gè)窗體類中添加一些函數(shù),比如void OnReceive(); void OnClose(); void OnAccept(); void OnConnect()等,它們會(huì)在我們編寫的的socket類中調(diào)用到。
void MySocket::OnAccept(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
if(nErrorCode==0)
{
((CServerDlg*)m_pDlg)->OnAccept();
}
CAsyncSocket::OnAccept(nErrorCode);
}
這里只寫了一個(gè)OnAccept()函數(shù),其他的幾個(gè)中也有類似的調(diào)用。詳細(xì)的請參考代碼。
email: ghs_linux@163.com
歡迎交流哦 :)