关于套接字的问题

simahao 2002-04-07 08:32:28
请问各位大虾,在C/S模式下,客户端通过创建一个套接字,可不可以利用此套接字通过循环来和多台服务器发送数据,如果不可以的话应如何处理?
谢谢!!!
...全文
124 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
saturday 2002-04-08
  • 打赏
  • 举报
回复
我就是要分,有分吗?哈哈,saturday7night@yahoo.com
记得分哟,老本都给你了

多播


#if !defined(AFX_MULTICASTSOCKET_H__269E2C7F_2037_11D3_8EF3_0000C0FD25F8__INCLUDED_)
#define AFX_MULTICASTSOCKET_H__269E2C7F_2037_11D3_8EF3_0000C0FD25F8__INCLUDED_

#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// MulticastSocket.h : header file
//

/////////////////////////////////////////////////////////////////////////////
// CMulticastSocket command target

class CMulticastSocket : public CAsyncSocket
{
// Attributes
public:

// Operations
public:
CMulticastSocket();
virtual ~CMulticastSocket();

// Overrides
public:
BOOL bDataReceived;
BOOL JoinGroup(CString, UINT, UINT, BOOL);
BOOL LeaveGroup();
BOOL SendTo(const void*, int);
void SetLoopBack(BOOL);
BOOL SetTTL(UINT nTTL);
BOOL CreateSendingSocket(UINT, BOOL);
BOOL CreateReceivingSocket(LPCTSTR, UINT);
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMulticastSocket)
public:
virtual void OnReceive(int nErrorCode);
//}}AFX_VIRTUAL

// Generated message map functions
//{{AFX_MSG(CMulticastSocket)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG

// Implementation
public:
char m_strBuffer[32000]; // Receiving buffer for the packet that has arrived
SOCKADDR_IN m_saHostGroup; // SOCKADDR structure to hold IP/Port of the Host group to send data to it
ip_mreq m_mrMReq; // Contains IP and interface of the host group
UINT m_nSendersPort; // Holds Port No. of the socket from which last packet was received
CString m_strSendersIP; // Hold IP of the socket from which the last packet was received
UINT m_nLocalPort; // Ephemeral port number of the sending port
CString m_strLocalIP; // IP Address of the local host or your machine
BOOL bForceNoLoopback; // If interface does not support lopback and the service is required, the bool is set to true
CAsyncSocket m_SendSocket; // Socket for sending data to the host group
};

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_MULTICASTSOCKET_H__269E2C7F_2037_11D3_8EF3_0000C0FD25F8__INCLUDED_)



// MulticastSocket.cpp : implementation file
//

#include "stdafx.h"
#include "CMulticastSocket.h"
#include "MulticastSocket.h"

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

/////////////////////////////////////////////////////////////////////////////
// CMulticastSocket

CMulticastSocket::CMulticastSocket()
{
bForceNoLoopback = FALSE;
bDataReceived = TRUE; /* Variable defined for this project. Not necessarily part of CMulticastSocket */
}

CMulticastSocket::~CMulticastSocket()
{
}


// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CMulticastSocket, CAsyncSocket)
//{{AFX_MSG_MAP(CMulticastSocket)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0

/////////////////////////////////////////////////////////////////////////////
// CMulticastSocket member functions

BOOL CMulticastSocket::CreateReceivingSocket(LPCTSTR strGroupIP, UINT nGroupPort)
{
/* Create socket for receiving packets from multicast group */
if(!Create(nGroupPort, SOCK_DGRAM, FD_READ))
return FALSE;

BOOL bMultipleApps = TRUE; /* allow reuse of local port if needed */
SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

/* Fill m_saHostGroup_in for sending datagrams */
memset(&m_saHostGroup, 0, sizeof(m_saHostGroup));
m_saHostGroup.sin_family = AF_INET;
m_saHostGroup.sin_addr.s_addr = inet_addr(strGroupIP);
m_saHostGroup.sin_port = htons((USHORT)nGroupPort);

/* Join the multicast group */
m_mrMReq.imr_multiaddr.s_addr = inet_addr(strGroupIP); /* group addr */
m_mrMReq.imr_interface.s_addr = htons(INADDR_ANY); /* use default */
if(setsockopt(m_hSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char FAR *)&m_mrMReq, sizeof(m_mrMReq)) < 0)
return FALSE;

return TRUE;
}

BOOL CMulticastSocket::CreateSendingSocket(UINT nTTL, BOOL bLoopBack)
{
if(!m_SendSocket.Create(0, SOCK_DGRAM, 0)) // Create an unconnected UDP socket
return FALSE;

if(!SetTTL(nTTL)) // Set Time to Live as specified by user
AfxMessageBox("Warning! Error Setting TTL");

SetLoopBack(bLoopBack); // Enable/Disable Loopback

return TRUE;
}

BOOL CMulticastSocket::SetTTL(UINT nTTL)
{
/* Set Time to Live to parameter TTL */
if(m_SendSocket.SetSockOpt(IP_MULTICAST_TTL, &nTTL, sizeof(int), IPPROTO_IP) == 0)
return FALSE; /* Error Setting TTL */
else
return TRUE; /* else TTL set successfully */
}

void CMulticastSocket::SetLoopBack(BOOL bLoop)
{
/* Set LOOPBACK option to TRUE OR FALSE according to IsLoop parameter */
int nLoopBack = (int)bLoop;
if(m_SendSocket.SetSockOpt(IP_MULTICAST_LOOP, &nLoopBack, sizeof(int), IPPROTO_IP) == 0)
{
if(!bLoop) /* if required to stop loopback */
{
bForceNoLoopback = TRUE; /* Internally making a note that loopback has to be disabled forcefilly */

// Get IP/Port for send socket in order to disable loopback forcefully */
char localHost[255];
gethostname(localHost, 255);
struct hostent *host = gethostbyname(localHost); /* Get local host IP */
m_strLocalIP = inet_ntoa (*(struct in_addr*)*host->h_addr_list);
CString Dummy; // Dummy string to be passed to the GetSockName function
m_SendSocket.GetSockName(Dummy, m_nLocalPort); /* Get Port Number for Sending Port */
}
}
}

void CMulticastSocket::OnReceive(int nErrorCode)
{
int nError = ReceiveFrom (m_strBuffer, 32000, m_strSendersIP, m_nSendersPort);
if(nError == SOCKET_ERROR)
AfxMessageBox("Error receiving data from the host group");
else
{
if (!bForceNoLoopback || (bForceNoLoopback && !(m_strSendersIP == m_strLocalIP && m_nSendersPort == m_nLocalPort)))
{
// 1. If loopbackback is not to be forced then interface handles the loopback itself
// 2. If you have to loopback and SOCKOPT LOOPBACK fails, no problem, interfaces loopback by default
// 3. If you have to stop loopback and SOCKOPT LOOPBACK fails, ignore messages coming from your own sending socket

// TODO : Add your code for here. The packet received is in m_strBuffer
bDataReceived = TRUE; /* Making note that a message has arrived */
}
}

CAsyncSocket::OnReceive(nErrorCode);
}

BOOL CMulticastSocket::LeaveGroup()
{
if(setsockopt (m_hSocket, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char FAR *)&m_mrMReq, sizeof(m_mrMReq)) < 0)
return FALSE;

m_SendSocket.Close(); // Close sending socket
Close(); // Close receving socket
return TRUE;
}

BOOL CMulticastSocket::SendTo(const void* strMessage, int nSize)
{
if(m_SendSocket.SendTo(strMessage, nSize, (SOCKADDR*)&m_saHostGroup, sizeof(SOCKADDR), 0) == SOCKET_ERROR)
return FALSE;
else
return TRUE;
}

BOOL CMulticastSocket::JoinGroup(CString GroupIP, UINT nGroupPort, UINT nTTL, BOOL bLoopback)
{
if(!CreateReceivingSocket(GroupIP, nGroupPort)) /* Create Socket for receiving and join the host group */
return FALSE;
if(!CreateSendingSocket(nTTL, bLoopback)) /* Create Socket for sending */
return FALSE;

return TRUE;
}
//CMulticastSocketDlg.h
private:
CMulticastSocket m_Socket;

//CMulticastSocketDlg.cpp
void CCMulticastSocketDlg::OnSend()
{
UpdateData(TRUE);
if(!m_Socket.SendTo(LPCTSTR(m_ChatMessage), m_ChatMessage.GetLength() + 1)) // Send message + NULL
AfxMessageBox("Send Failed!");

m_ChatMessage = ""; /* Clear the Send message field */
UpdateData(FALSE);
}
chenAxue 2002-04-08
  • 打赏
  • 举报
回复
用非阻塞模式也可以实现。是不是就可以不用循环。
simahao 2002-04-08
  • 打赏
  • 举报
回复
不好意思DISCONNECT 是那个类的函数,好象不是Casynccsocket类的
tcice 2002-04-08
  • 打赏
  • 举报
回复
不是跟你说了吗,你先disconnect然后再connect
simahao 2002-04-08
  • 打赏
  • 举报
回复
结果是提示是不能把一个以建立的套接字再次建立连接,但是我还不想通过再次建立套接字来建立连接,这样应如何处理。
谢谢非凡兄台,再次请教!
llhwan 2002-04-07
  • 打赏
  • 举报
回复
这说明:
在一个已经连接的套接字上做了一个连接请求!
在VC中用Error Lookup工具可以查到
simahao 2002-04-07
  • 打赏
  • 举报
回复
还有一个问题,我用GetLastError()函数返回Connect的错误,调试信息为10056,这是什么意思,msdn中没有有关的解释呀
llhwan 2002-04-07
  • 打赏
  • 举报
回复
好像是用BOOL SetSockOpt( int nOptionName, const void* lpOptionValue, int nOptionLen, int nLevel = SOL_SOCKET );来设置socket的广播属性,具体的请查msdn!

ychener 2002-04-07
  • 打赏
  • 举报
回复
当然是在客户端建立一个服务器列表
并且对每个服务器都建立一个连接(a new SOCKET)

不久搞定
snsins 2002-04-07
  • 打赏
  • 举报
回复
那就使用多播
比广播更好
simahao 2002-04-07
  • 打赏
  • 举报
回复
请问非凡兄台,如何广播(请详细)
多谢!
longyii 2002-04-07
  • 打赏
  • 举报
回复
还不如不建立连接,用UDP呢
snsins 2002-04-07
  • 打赏
  • 举报
回复
可以

每和一台服务器发送数据完成后,就DisConnect
然后再和另外的服务器Connect
llhwan 2002-04-07
  • 打赏
  • 举报
回复
应该可以的,
要给多台服务器发送数据,还不如把数据包广播出去呀!
simahao 2002-04-07
  • 打赏
  • 举报
回复
继续关注!

16,473

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧