服务器和客户机采用Socket编程。
问题1:服务器进入侦听状态,但是此时客户端并不知道服务器的地址。我该如何做?问题2:我想使客户端先发出一个广播,服务器接受广播后给客户机发送自己的Ip等信息。
接着再建立Socket通讯。这样对吗?问题3:是不是进行广播必须是数据报SOCK_DGRAM 问题4:是不是通讯的双方必须都是数据流或数据报?如果服务器是数据流SOCK_STREAM套接字,而客户机是数据报套接字就不能够通讯?我是网络编程新手,向各位请教!如果有相类似的源码就更佳!先谢过

解决方案 »

  1.   

    1、用广播(或组播)方式,客户端不需道服务器的地址,初始化时用程序建立一个新的广播地址。
    2、用广播(或组播)方式,可直接收发数据。不用侦听。
    3、是;
    4、只要是数据就行。
    例子:// MSGSocket.cpp : implementation file
    //#include "stdafx.h"
    //#include "AV8Rcvr.h"
    #include "MSGSocket.h"#ifdef _DEBUG
    #define new DEBUG_NEW
    #undef THIS_FILE
    static char THIS_FILE[] = __FILE__;
    #endif/////////////////////////////////////////////////////////////////////////////
    // CMSGSocketCMSGSocket::CMSGSocket()
    {
    bForceNoLoopback = FALSE;
    bDataReceived = false; /* Variable defined for this project. Not necessarily part of CMsocket */
    number=0;
    for(int i=0;i<40;i++)
    {
    ready[i]=false;
    }
    number=0;
    newfile=false;
    receivenumber=0;
    filename="";
    }CMSGSocket::~CMSGSocket()
    {
    }
    // Do not edit the following lines, which are needed by ClassWizard.
    #if 0
    BEGIN_MESSAGE_MAP(CMSGSocket, CSocket)
    //{{AFX_MSG_MAP(CMSGSocket)
    //}}AFX_MSG_MAP
    END_MESSAGE_MAP()
    #endif // 0/////////////////////////////////////////////////////////////////////////////
    // CMSGSocket member functions
    BOOL CMSGSocket::CreateSocket(LPCTSTR strGroupIP, UINT nGroupPort)
    {
    /* Create socket for receiving packets from multicast group */
    LeaveGroup();
    //if(!Create(nGroupPort, SOCK_DGRAM, FD_READ|FD_WRITE))  //CAsyncSocket
    if(!Create(nGroupPort, SOCK_DGRAM, NULL))  //CSocket
    {
    AfxMessageBox("建立连接时出错,检查该频道是否已被别的窗口占用!");
    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)
    {
    AfxMessageBox("CreateReceivingSocket failed");
    return FALSE;
    } return TRUE;
    }void CMSGSocket::OnReceive(int nErrorCode)
    {
    ::SetActiveWindow(AfxGetApp()->m_pMainWnd->m_hWnd);
    //AfxMessageBox("MSG收到数据!");
    //return;
    int nError = ReceiveFrom (&msg_commanddata,sizeof(csock_data), 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)))
    {
    //lyksetdata1(3);
    //AfxMessageBox("MSG收到数据!");
    ::PostMessage(GetActiveWindow( ),WM_COMMAND,WM_RECEIVEMSG,(LPARAM)0);
    }
    }
    CSocket::OnReceive(nErrorCode); 
    }
    BOOL CMSGSocket::LeaveGroup()
    {
    if(setsockopt (m_hSocket, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char FAR *)&m_mrMReq, sizeof(m_mrMReq)) < 0)
    return FALSE; Close(); // Close receving socket
    return TRUE;
    }/*
    BOOL CMSGSocket::Send(const void* strMessage, int nSize)
    {
    //CString str=strMessage;
    //AfxMessageBox(str); if(SendTo(strMessage, nSize, (SOCKADDR*)&m_saHostGroup, sizeof(SOCKADDR), 0) == SOCKET_ERROR)
    return FALSE;
    else
    return TRUE;
    }
    */
    BOOL CMSGSocket::Send(csock_data m_data1)
    {

    if(SendTo(&m_data1, sizeof(csock_data), (SOCKADDR*)&m_saHostGroup, sizeof(SOCKADDR), 0) == SOCKET_ERROR)
    {
         return FALSE;
    }
    else
    {
    //AfxMessageBox("MSGSend!");
    return TRUE;
    }
    }BOOL CMSGSocket::TextSend(CString str)
    {
    CString st=str;
    st+="/@&/";
    //BOOL bo=Send(st, st.GetLength()+1);
    return 0;
    }BOOL CMSGSocket::GetMaker(void)
    {
    return bDataReceived;
    }void CMSGSocket::SetMaker(BOOL da)
    {
    bDataReceived=da;
    //ready[number]==da;
    }void CMSGSocket::Init(void)
    {
    bForceNoLoopback = FALSE;
    bDataReceived = false; /* Variable defined for this project. Not necessarily part of CMSGSocket */
    number=0;
    for(int i=0;i<40;i++)
    {
    ready[i]=false;
    }
    }
    BOOL CMSGSocket::SendFile(CString filename)
    {
    return 0;
    }void CMSGSocket::ReadFile()
    {}BOOL CMSGSocket::SendData(SOCKET_STREAM_FILE_INFO m_data1)
    {
    //AfxMessageBox("send........");
    if(SendTo(&m_data1, sizeof(SOCKET_STREAM_FILE_INFO), (SOCKADDR*)&m_saHostGroup, sizeof(SOCKADDR), 0) == SOCKET_ERROR)
    {
    //AfxMessageBox("send false");
         return FALSE;
    }
    else
    {
    //AfxMessageBox("send ok");
    return TRUE;
    }
    }
      

  2.   

    #if !defined(AFX_MSGSocket_H__257F140C_C139_4112_BACA_2C16C0F155B8__INCLUDED_)
    #define AFX_MSGSocket_H__257F140C_C139_4112_BACA_2C16C0F155B8__INCLUDED_#if _MSC_VER > 1000
    #pragma once
    #endif // _MSC_VER > 1000
    // MSGSocket.h : header file
    ///////////////////////////////////////////////////////////////////////////////
    // CMSGSocket command targetclass CMSGSocket : public CSocket
    {
    // Attributes
    public:
    char m_strBuffer[32768];
    char m_strBuffer1[32768];
    char m_strBuffer2[32768]; // 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 BOOL bDataReceived;
    BOOL LeaveGroup();
    //BOOL Send(const void*, int);
    BOOL Send(csock_data m_data1);
    BOOL CreateSocket(LPCTSTR, UINT);
    BOOL ready[40];
    int number;
    CString text; ////////////////
    csock_data msg_commanddata; BOOL newfile;
    DWORD fileID;
    DWORD  receivenumber;
    CString filename; BOOL GetMaker(void);
    void SetMaker(BOOL da);
    void ReadFrom(void);
    void Init(void);
    BOOL TextSend(CString text); BOOL SendFile(CString filename);
    void ReadFile(void);
    BOOL SendData(SOCKET_STREAM_FILE_INFO m_data1);
    /////////////////////
    ////////////////
    HINSTANCE glib;
    LYKGETDATA lykgetdata1;
    LYKSETDATA lyksetdata1;
    // Operations
    public:
    CMSGSocket();
    virtual ~CMSGSocket();// Overrides
    public:
    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CMSGSocket)
    public:
    virtual void OnReceive(int nErrorCode);
    //}}AFX_VIRTUAL // Generated message map functions
    //{{AFX_MSG(CMSGSocket)
    // NOTE - the ClassWizard will add and remove member functions here.
    //}}AFX_MSG// Implementation
    protected:
    };///////////////////////////////////////////////////////////////////////////////{{AFX_INSERT_LOCATION}}
    // Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif // !defined(AFX_MSGSocket_H__257F140C_C139_4112_BACA_2C16C0F155B8__INCLUDED_)用法是:void CMainFrame::SendMSG(int pcommand,int pmsg)
    {
    if(!MSG_Socket.CreateSocket("234.5.6.7", 206))
    AfxMessageBox("建立网络连接出错!"); //AfxMessageBox("SendMSG");
    //return;
    //AfxMessageBox("aa");
    ::memset(&msg_commanddata,0,sizeof(csock_data));
    msg_commanddata.command=pcommand;
    msg_commanddata.serial=pmsg;
    POINT pt;
    GetCursorPos(&pt);
    msg_commanddata.mousex=pt.x;
    msg_commanddata.mousey=pt.y;
    //////////////
    char ch[128];
        ::gethostname(ch,100);
    hostent* tent=::gethostbyname(ch);
    msg_commanddata.IP[0][0]=(byte)tent->h_addr[0];
    msg_commanddata.IP[0][1]=(byte)tent->h_addr[1];
    msg_commanddata.IP[0][2]=(byte)tent->h_addr[2];
    msg_commanddata.IP[0][3]=(byte)tent->h_addr[3];

    ///////////////////////////////////////////
    if(!MSG_Socket.Send(msg_commanddata))
    {
    //
    for(int i=0;i<3;i++)
    {
    //Sleep(100);
    if(!MSG_Socket.Send(msg_commanddata))
    {
    //AfxMessageBox("send data failed");
                 //return;
    }
    else
    {
                     //AfxMessageBox("send data failed");
    }
    }
    }
    else
    {
    }
    //AfxMessageBox("send end");
    //return;
    }