① 關於CSocket的三個實際問題!
剛才看錯了MSDN上的解釋是這樣的
CSocket::Create
Call the Create member function after constructing a socket object to create the Windows socket and attach it.
BOOL Create(
UINT nSocketPort = 0,
int nSocketType = SOCK_STREAM,
LPCTSTR lpszSocketAddress = NULL
);
Parameters
nSocketPort
A particular port to be used with the socket, or 0 if you want MFC to select a port.
nSocketType
SOCK_STREAM or SOCK_DGRAM.
lpszSocketAddress
A pointer to a string containing the network address of the connected socket, a dotted number such as "128.56.22.8".
Return Value
Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError.
Remarks
Create then calls Bind to bind the socket to the specified address. The following socket types are supported:
SOCK_STREAM Provides sequenced, reliable, two-way, connection-based byte streams. Uses Transmission Control Protocol (TCP) for the Internet address family.
SOCK_DGRAM Supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length. Uses User Datagram Protocol (UDP) for the Internet address family. To use this option, you must not use the socket with a CArchive object.
Note
The Accept member function takes a reference to a new, empty CSocket object as its parameter. You must construct this object before you call Accept. Keep in mind that if this socket object goes out of scope, the connection closes. Do not call Create for this new socket object.
----------------------
sendto
The sendto function sends data to a specific destination.
int sendto(
SOCKET s,
const char* buf,
int len,
int flags,
const struct sockaddr* to,
int tolen
);
Parameters
s
[in] Descriptor identifying a (possibly connected) socket.
buf
[in] Buffer containing the data to be transmitted.
len
[in] Length of the data in buf, in bytes.
flags
[in] Indicator specifying the way in which the call is made.
to
[in] Optional pointer to a sockaddr structure that contains the address of the target socket.
tolen
[in] Size of the address in to, in bytes.
Return Values
If no error occurs, sendto returns the total number of bytes sent, which can be less than the number indicated by len. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
Error code Meaning
WSANOTINITIALISED A successful WSAStartup call must occur before using this function.
WSAENETDOWN The network subsystem has failed.
WSAEACCES The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST parameter to allow the use of the broadcast address.
WSAEINVAL An unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled.
WSAEINTR A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.
WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
WSAEFAULT The buf or to parameters are not part of the user address space, or the tolen parameter is too small.
WSAENETRESET The connection has been broken e to keep-alive activity detecting a failure while the operation was in progress.
WSAENOBUFS No buffer space is available.
WSAENOTCONN The socket is not connected (connection-oriented sockets only).
WSAENOTSOCK The descriptor is not a socket.
WSAEOPNOTSUPP MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only receive operations.
WSAESHUTDOWN The socket has been shut down; it is not possible to sendto on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
WSAEWOULDBLOCK The socket is marked as nonblocking and the requested operation would block.
WSAEMSGSIZE The socket is message oriented, and the message is larger than the maximum supported by the underlying transport.
WSAEHOSTUNREACH The remote host cannot be reached from this host at this time.
WSAECONNABORTED The virtual circuit was terminated e to a time-out or other failure. The application should close the socket as it is no longer usable.
WSAECONNRESET The virtual circuit was reset by the remote side executing a hard or abortive close. For UPD sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a "Port Unreachable" ICMP packet. The application should close the socket as it is no longer usable.
WSAEADDRNOTAVAIL The remote address is not a valid address, for example, ADDR_ANY.
WSAEAFNOSUPPORT Addresses in the specified family cannot be used with this socket.
WSAEDESTADDRREQ A destination address is required.
WSAENETUNREACH The network cannot be reached from this host at this time.
WSAEHOSTUNREACH A socket operation was attempted to an unreachable host.
WSAETIMEDOUT The connection has been dropped, because of a network failure or because the system on the other end went down without notice.
Remarks
The sendto function is used to write outgoing data on a socket. For message-oriented sockets, care must be taken not to exceed the maximum packet size of the underlying subnets, which can be obtained by using getsockopt to retrieve the value of socket option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying protocol, the error WSAEMSGSIZE is returned and no data is transmitted.
The to parameter can be any valid address in the socket's address family, including a broadcast or any multicast address. To send to a broadcast address, an application must have used setsockopt with SO_BROADCAST enabled. Otherwise, sendto will fail with the error code WSAEACCES. For TCP/IP, an application can send to any multicast address (without becoming a group member).
Note If a socket is opened, a setsockopt call is made, and then a sendto call is made, Windows Sockets performs an implicit bind function call.
If the socket is unbound, unique values are assigned to the local association by the system, and the socket is then marked as bound. An application can use getsockname to determine the local socket name in this case.
The successful completion of a sendto does not indicate that the data was successfully delivered.
The sendto function is normally used on a connectionless socket to send a datagram to a specific peer socket identified by the to parameter. Even if the connectionless socket has been previously connected to a specific address, the to parameter overrides the destination address for that particular datagram only. On a connection-oriented socket, the to and tolen parameters are ignored, making sendto equivalent to send.
這些你可以查看MSDN,上面都有很詳細的解釋的。
② MFC CSocket編程, error C2065: 「IDP_SOCKETS_INIT_FAILED」: 未聲明的標識符。各位大神幫幫忙啊,謝謝了
你在建立MFC工程的時候沒有選用SOCKET選項。。所以他有些資源沒有給你加進去。。。
你在資源文件裡面的Resource.h裡面加一行
#define IDP_SOCKETS_INIT_FAILED 103
應該就可以了(不過我在網上看別人的帖子的時候看到過不是103而是104的我也不知道怎麼回事,103是我自己電腦上自動帶出來的值)
③ CSocket之UDP編程
#include <stdio.h>
#include <Winsock2.h>
#pragma comment(lib,"ws2_32.lib")
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1);
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 )
{
WSACleanup( );
return;
}
SOCKET sersocket=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN seraddr;
seraddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
seraddr.sin_family=AF_INET;
seraddr.sin_port=htons(5000);
bind(sersocket,(SOCKADDR*)&seraddr,sizeof(SOCKADDR));
SOCKADDR clientaddr;
int len=sizeof(SOCKADDR);
char revbuf[100];
char sendbuf[100];
recvfrom(sersocket,revbuf,100,0,(SOCKADDR*)&clientaddr,&len);
printf("%s\n",revbuf);
scanf("%s",&sendbuf);
sendto(sersocket,sendbuf,strlen(sendbuf)+1,0,(SOCKADDR*)&clientaddr,len);
closesocket(sersocket);
WSACleanup();
}
#include <stdio.h>
#include <Winsock2.h>
#pragma comment(lib,"ws2_32.lib")
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1);
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 )
{
WSACleanup( );
return;
}
SOCKET sockclient=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN clientaddr;
clientaddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
clientaddr.sin_family=AF_INET;
clientaddr.sin_port=htons(5000);
int len=sizeof(SOCKADDR);
char revbuf[100];
char sendbuf[100];
printf("請輸入內容:\n");
while(1)
{
scanf("%s",&sendbuf);
sendto(sockclient,sendbuf,strlen(sendbuf)+1,0,(SOCKADDR*)&clientaddr,len);
recvfrom(sockclient,revbuf,100,0,(SOCKADDR*)&clientaddr,&len);
printf("%s\n",revbuf);
}
closesocket(sockclient);
WSACleanup();
}
大同小異,CSocket只是進行了封裝而已,原理是一樣的,編程要思路靈活才行。
④ 基於mfc的socket編程怎麼進行文件傳輸
1. 採用了多線程的方法,文件傳輸時使用AfxBeginThread()開啟新線程
void CClientsockDlg::OnBnClickedSend()
{
pThreadSend = AfxBeginThread(Thread_Send,this);/
}
文件的發送和接收都開起了新線程
UINTThread_Send(LPVOID lpParam)
{
代碼略…
}
2. 支持從配置文件configuration.ini中獲取伺服器參數
採用GetPrivateProfileString()和GetPrivateProfileInt()分別獲取位於ServerConfiguration.ini文件中的String類型的IP和int類型的port
CString IP;
int port;
GetPrivateProfileString
(L"ServerConfiguration",L"IP",L"沒有讀取到數據!",IP.GetBuffer(10),10,L".\\configuration.ini");
port=GetPrivateProfileInt(L"ServerConfiguration",L"port",0,L".\\configuration.ini");
3. 採用了面向對象的設計方式,功能之間按模塊劃分
MFC本身具有良好的面向對象的特性,本程序嚴格按照MFC框架結構編寫代碼,每個按鈕對應一個功能函數,降低了代碼之間的耦合性,有利於程序的擴展和復用。
void CServersockDlg::OnBnClickedChoose()
void CServersockDlg::OnBnClickedSend()
void CServersockDlg::OnBnClickedRecvdata()
void CServersockDlg::OnBnClickedAbout()
void CServersockDlg::OnBnClickedWriteini()
4. 採用了CSocket類,代碼相對更簡單
CSocket類是MFC框架對socket編程中的winsockAPI的封裝,因此通過這個類管理收發數據更加便利。代碼也跟那個既簡單易懂。
//創建
if(!Clientsock.Socket())
{
CString str;
str.Format(_T("Socket創建失敗:%d"),GetLastError());
AfxMessageBox(str);
}
//連接
if(!Clientsock.Connect(IP,port))
{
CString str;
str.Format(_T("Socket連接失敗:%d"),GetLastError());
AfxMessageBox(str);
}
else
{
AfxMessageBox(_T("Socket連接成功"));
代碼略…
//發送
while(nSize<FindFileData.nFileSizeLow)
{
szBuff = new char[1024];
memset(szBuff,0x00,1024);
nSend =file.Read(szBuff,1024);
Clientsock.Send(szBuff,nSend);//發送數據
nSize += nSend;
}
file.Close();
delete szBuff;
Clientsock.Close();
(dlg->GetDlgItem(IDC_SEND))->EnableWindow(TRUE);
AfxMessageBox(_T("文件發送成功"));
dlg->SetDlgItemTextW(IDC_FILEPATHNAME,_T(""));
}
return 0;
5. 支持數據在伺服器與客戶端之間雙向傳輸
本程序不但可以從客戶端往伺服器端傳文件,而且可以從伺服器端往客戶端傳文件。
但是互傳文件的方式並不是完全相同的。
伺服器端不管是接收文件還是發送文件始終是對綁定的埠進行監聽。
//綁定
if(!Serversock.Bind(port))
{
CString str;
str.Format(_T("Socket綁定失敗: %d"),GetLastError());
AfxMessageBox(str);
}
//監聽
if(!Serversock.Listen(10))
{
CString str;
str.Format(_T("Socket監聽失敗:%d"),GetLastError());
AfxMessageBox(str);
}
客戶端不管是接收文件還是發送文件始終是進行連接。
if(!Clientsock.Connect(IP,port))
{
CString str;
str.Format(_T("Socket連接失ì敗:%d"),GetLastError());
AfxMessageBox(str);
}
else
{
略…
6. 完全圖形化操作界面
二.軟體使用說明
客戶端主界面如圖所示:
單擊「選擇文件」彈出文件對話框,選擇一個要發送的文件,同時保存文件的路徑。
單擊「發送」則會讀取ServerConfiguration.ini文件中的配置信息(IP和port),並根據此信息建立Socket連接,發送文件。注意:伺服器端應該先單擊了「接受客戶端數據」,否則發送失敗。
單擊「接收」也會讀取ServerConfiguration.ini文件中的配置信息(IP和port),並根據此信息建立Socket連接,接收文件。注意:伺服器端應該先選擇了向客戶端發送的文件,並單擊了「發送」,否則接受失敗。
單擊「讀取配置文件」,會從ServerConfiguration.ini文件中讀取配置信息,並以可編輯的文本形式顯示出來,修改完後,單擊「寫入配置文件」,會將修改後的信息保存到配置文件中。
單擊「關於」可以了解到軟體相關信息。
代碼注釋里有更詳細的說明
伺服器端主界面如圖所示
u 單擊「接受客戶端數據」,開始監聽客戶端的鏈接。
u 單擊「選擇文件」彈出文件對話框,選擇一個要發送的文件,同時保存文件的路徑。
u 單擊「發送」則會讀取ServerConfiguration.ini文件中的配置信息(port),並監聽對應埠,准備發送文件。注意:客戶端選擇「接收」以後才能發送成功。
u 單擊「讀取配置文件」,會從ServerConfiguration.ini文件中讀取配置信息,並以可編輯的文本形式顯示出來,修改完後,單擊「寫入配置文件」,會將修改後的信息保存到配置文件中。但是伺服器的IP是不可以修改的,它是在程序開始運行時從伺服器所在機器的網卡上獲取的。
u 單擊「關於」可以了解到軟體相關信息。
u 代碼注釋里有更詳細的說明
代碼下載地址:http://download.csdn.net/detail/leixiaohua1020/6320417
在此附上客戶端使用CSocket發起連接的代碼
[cpp] view plain
//----------------------------發送文件的線程------------------------------
UINT Thread_Send(LPVOID lpParam)
{
CClientsockDlg *dlg=(CClientsockDlg *)lpParam;
(dlg->GetDlgItem(IDC_SEND))->EnableWindow(FALSE);
CSocket Clientsock; //definition socket.
if(!AfxSocketInit())
{
AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
}
CString IP;
int port;
GetPrivateProfileString(L"ServerConfiguration",L"IP",L"沒有讀取到數據!",IP.GetBuffer(100),100,L".\\configuration.ini");
port=GetPrivateProfileInt(L"ServerConfiguration",L"port",0,L".\\configuration.ini");
//創建
if(!Clientsock.Socket())
{
CString str;
str.Format(_T("Socket創建失敗: %d"),GetLastError());
AfxMessageBox(str);
}
//連接
// if(!Clientsock.Connect(_T("127.0.0.1"),8088))
if(!Clientsock.Connect(IP,port))
{
CString str;
str.Format(_T("Socket連接失敗: %d"),GetLastError());
AfxMessageBox(str);
}
else
{
AfxMessageBox(_T("Socket連接成功"));
WIN32_FIND_DATA FindFileData;
CString strPathName; //定義用來保存發送文件路徑的CString對象
dlg->GetDlgItemTextW(IDC_FILEPATHNAME,strPathName);
FindClose(FindFirstFile(strPathName,&FindFileData));
Clientsock.Send(&FindFileData,sizeof(WIN32_FIND_DATA));
CFile file;
if(!file.Open(strPathName,CFile::modeRead|CFile::typeBinary))
{
AfxMessageBox(_T("文件不存在"));
return 1;
}
UINT nSize = 0;
UINT nSend = 0;
char *szBuff=NULL;
//發送
while(nSize<FindFileData.nFileSizeLow)
{
szBuff = new char[1024];
memset(szBuff,0x00,1024);
nSend = file.Read(szBuff,1024);
Clientsock.Send(szBuff,nSend);//發送數據
nSize += nSend;
}
file.Close();
delete szBuff;
Clientsock.Close();
(dlg->GetDlgItem(IDC_SEND))->EnableWindow(TRUE);
AfxMessageBox(_T("文件發送成功"));
dlg->SetDlgItemTextW(IDC_FILEPATHNAME,_T(""));
}
return 0;
}
以及伺服器端使用CSocket監聽的代碼:
[cpp] view plain
//----------------------------監聽文件的線程------------------------------
UINT Thread_Func(LPVOID lpParam) //接收文件的線程函數
{
CServersockDlg *dlg = (CServersockDlg *)lpParam; //獲取對話框指針
(dlg->GetDlgItem(IDC_RECVDATA))->EnableWindow(FALSE);
if(!AfxSocketInit())
{
AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
}
CString IP;
int port;
GetPrivateProfileString(L"ServerConfiguration",L"IP",L"沒有讀取到數據!",IP.GetBuffer(100),100,L".\\configuration.ini");
port=GetPrivateProfileInt(L"ServerConfiguration",L"port",0,L".\\configuration.ini");
char errBuf[100]={0};// 臨時緩存
SYSTEMTIME t; //系統時間結構
CFile logErrorfile;
if(!logErrorfile.Open(_T("logErrorfile.txt"),CFile::modeCreate|CFile::modeReadWrite))
{
return 1;
}
CSocket Serversock;
CSocket Clientsock;
//創建
if(!Serversock.Socket())
{
CString str;
str.Format(_T("Socket創建失敗: %d"),GetLastError());
AfxMessageBox(str);
}
BOOL bOptVal = TRUE;
int bOptLen = sizeof(BOOL);
Serversock.SetSockOpt(SO_REUSEADDR,(void *)&bOptVal,bOptLen,SOL_SOCKET);
//綁定
if(!Serversock.Bind(port))
{
CString str;
str.Format(_T("Socket綁定失敗: %d"),GetLastError());
AfxMessageBox(str);
}
//監聽
if(!Serversock.Listen(10))
{
CString str;
str.Format(_T("Socket監聽失敗: %d"),GetLastError());
AfxMessageBox(str);
}
GetLocalTime(&t);
sprintf_s(errBuf,"伺服器已經啟動...正在等待接收文件...\r\n時間:%d年%d月%d日 %2d:%2d:%2d \r\n",t.wYear,t.wMonth,t.wDay,
t.wHour,t.wMinute,t.wSecond);
int len = strlen(errBuf);
logErrorfile.Write(errBuf,len);
AfxMessageBox(_T("啟動成功等待接收文件"));
while(1)
{
//AfxMessageBox(_T("伺服器啟動成功..."));
if(!Serversock.Accept(Clientsock)) //等待接收
{
continue;
}
else
{
WIN32_FIND_DATA FileInfo;
Clientsock.Receive(&FileInfo,sizeof(WIN32_FIND_DATA));
CFile file;
file.Open(FileInfo.cFileName,CFile::modeCreate|CFile::modeWrite);
//AfxMessageBox(FileInfo.cFileName);
int length = sizeof(FileInfo.cFileName);
logErrorfile.Write(FileInfo.cFileName,length);
//Receive文件的數據
UINT nSize = 0;
UINT nData = 0;
char *szBuff=NULL;
while(nSize<FileInfo.nFileSizeLow)
{
szBuff = new char[1024];
memset(szBuff,0x00,1024);
nData=Clientsock.Receive(szBuff,1024);
file.Write(szBuff,nData);
nSize+=nData;
}
delete szBuff;
Serversock.Close();
Clientsock.Close();
file.Close();
(dlg->GetDlgItem(IDC_RECVDATA))->EnableWindow(TRUE);
sprintf_s(errBuf,"文件接收成功...\r\n時間:%d年%d月%d日 %2d:%2d:%2d \r\n",t.wYear,t.wMonth,t.wDay,
t.wHour,t.wMinute,t.wSecond);
int len = strlen(errBuf);
logErrorfile.Write(errBuf,len);
//AfxMessageBox(_T("文件接收成功..."));
break;
}
}
return 0;
}