导航:首页 > 编程语言 > csocket编程从入门到精通

csocket编程从入门到精通

发布时间:2023-08-27 01:00:38

① 关于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;
}

阅读全文

与csocket编程从入门到精通相关的资料

热点内容
空调压缩机排空气视频 浏览:283
centos72nginxphp 浏览:184
游戏平台用什么服务器好 浏览:753
保密柜里的图片是加密文件吗 浏览:909
php判断最后一个字符 浏览:635
pdf脑区 浏览:635
at命令已弃用 浏览:490
买点卖出指标源码 浏览:612
36位单片机 浏览:428
英雄联盟山东服务器地址 浏览:212
sd服务器什么意思 浏览:617
thinkphp去indexphp 浏览:62
电脑显示连接未加密 浏览:193
zao服务器怎么修改 浏览:244
php使用jsapi调起支付 浏览:891
vivo云服务器网 浏览:722
cmd远程连接命令行 浏览:961
黑马python讲义 浏览:133
php高并发测试 浏览:88
第二届程序员节开幕式 浏览:84