| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 621 人关注过本帖
标题:网络通信服务端程序问题
只看楼主 加入收藏
qwe885167759
Rank: 4
等 级:业余侠客
威 望:5
帖 子:148
专家分:259
注 册:2013-3-12
结帖率:72.22%
收藏
已结贴  问题点数:10 回复次数:1 
网络通信服务端程序问题
// 网络通信ServerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "网络通信Server.h"
#include "网络通信ServerDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
    CAboutDlg();

// Dialog Data
    //{{AFX_DATA(CAboutDlg)
    enum { IDD = IDD_ABOUTBOX };
    //}}AFX_DATA

    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CAboutDlg)
    protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
    //}}AFX_VIRTUAL

// Implementation
protected:
    //{{AFX_MSG(CAboutDlg)
    //}}AFX_MSG
    DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
    //{{AFX_DATA_INIT(CAboutDlg)
    //}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CAboutDlg)
    //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
    //{{AFX_MSG_MAP(CAboutDlg)
        // No message handlers
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CServerDlg dialog

CServerDlg::CServerDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CServerDlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CServerDlg)
    m_status = _T("");
    m_recv = _T("");
    m_send = _T("");
    //}}AFX_DATA_INIT
    // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CServerDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CServerDlg)
    DDX_Text(pDX, IDC_STATUS, m_status);
    DDX_Text(pDX, IDC_RECV, m_recv);
    DDX_Text(pDX, IDC_SEND, m_send);
    //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CServerDlg, CDialog)
    //{{AFX_MSG_MAP(CServerDlg)
    ON_WM_SYSCOMMAND()
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    ON_BN_CLICKED(IDC_STARTRUN, OnStartrun)
    ON_MESSAGE(WM_SOCKET,OnSocket)
    ON_BN_CLICKED(IDC_SENDBTN, OnSendbtn)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CServerDlg message handlers

BOOL CServerDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    // Add "About..." menu item to system menu.

    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        CString strAboutMenu;
        strAboutMenu.LoadString(IDS_ABOUTBOX);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);            // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon
   
    // TODO: Add extra initialization here
   
    return TRUE;  // return TRUE  unless you set the focus to a control
}

void CServerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
    if ((nID & 0xFFF0) == IDM_ABOUTBOX)
    {
        CAboutDlg dlgAbout;
        dlgAbout.DoModal();
    }
    else
    {
        CDialog::OnSysCommand(nID, lParam);
    }
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CServerDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting

        SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;

        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialog::OnPaint();
    }
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CServerDlg::OnQueryDragIcon()
{
    return (HCURSOR) m_hIcon;
}

void CServerDlg::OnStartrun()
{
    // TODO: Add your control notification handler code here

    //加载Winsock dll
    WORD    version = MAKEWORD(2,0);
    WSADATA wsadata;
    if(WSAStartup(version,&wsadata))
    {
        MessageBox("加载Winsock dll 失败");
        return;
    }

    //创建套接字
    socket_server = socket(AF_INET,SOCK_STREAM,NULL);
    if(INVALID_SOCKET == socket_server)
    {
        MessageBox("套接字创建失败");
        return;
    }

    char hostname[20] = "";
    if(gethostname(hostname,20))
    {
        MessageBox("主机名获取失败");
        return;
    }

    hostent *htent = gethostbyname(hostname);
    if(htent == NULL)
    {
        MessageBox("主机IP获取失败");
        return;
    }
   
//     char pIp[4] = htent->h_addr_list[0];
//     IN_ADDR addrIp;
//     memmove(&addrIp,pIp,4);

    LPSTR lpAddr = htent->h_addr_list[0];
    IN_ADDR inAddr;
    memmove(&inAddr,lpAddr,4);
    CString ipAddress = inet_ntoa(inAddr);

    SOCKADDR_IN addr;
    memset(&addr,0,sizeof(SOCKADDR_IN));
    addr.sin_family    = AF_INET;
    addr.sin_port    = htons(80);
    addr.sin_addr.S_un.S_addr = inet_addr(ipAddress);

    //绑定套接字
    if(!bind(socket_server,(sockaddr *)&addr,sizeof(sockaddr)) )
    {
        MessageBox("绑定IP和port出错");
        return;
    }
    //监听
    if(!listen(socket_server,SOMAXCONN) )
    {
        MessageBox("监听出错");
        return;
    }

    if( WSAAsyncSelect(socket_server,this->m_hWnd,WM_SOCKET,FD_ACCEPT | FD_READ))
    {
        MessageBox("异步设置出错");
        return;
    }
}



void CServerDlg::OnCancel()
{
    // TODO: Add extra cleanup here

    if(WSACleanup())
    {
        MessageBox("卸载Winsock dll失败");
        return;
    }
    if(socket_server)
        closesocket(socket_server);
    if(socket_client)
        closesocket(socket_client);
    CDialog::OnCancel();
}

void CServerDlg::OnSocket(WPARAM wParam,LPARAM lParam)
{
    switch(lParam)
    {
    case FD_ACCEPT:
         {
             SOCKADDR_IN addr;
             int len = sizeof(SOCKADDR_IN);
             socket_client = accept(socket_server,(sockaddr *)&addr,&len);
             if(socket_client == INVALID_SOCKET)
             {
                 MessageBox("客户端套接字创建出错");
                 return;
             }
             //获取对方ip
             m_status += "客户端IP:";
             m_status += inet_ntoa(addr.sin_addr);
             UpdateData(false);
         }
        break;
    case FD_READ:
        {
            UpdateData(true);
            char buff[1024] = "";
            if(!recv(socket_client,buff,1024,NULL))
            {
                MessageBox("数据接收出错");
                return;
            }
            m_recv += "\r\n客户端:";
            m_recv += buff;
            UpdateData(false);
        }
    }
}

void CServerDlg::OnSendbtn()
{
    // TODO: Add your control notification handler code here
    UpdateData(true);
    if(SOCKET_ERROR == send(socket_client,m_send.GetBuffer(1),
        m_send.GetLength(),NULL) )
    {
        MessageBox("消息发送出错");
        return;
    }
    m_recv += "\r\n服务器端:";
    m_recv += m_send;
    m_send = "";
    UpdateData(false);
}

运行提示绑定端口和IP出错
搜索更多相关主题的帖子: include public 服务端 通信 
2014-08-19 14:43
邵帅
Rank: 7Rank: 7Rank: 7
等 级:贵宾
威 望:20
帖 子:174
专家分:505
注 册:2012-8-27
收藏
得分:10 
80端口为知名端口,自己写的程序不要使用。自己使用的端口范围为1024到49151。0到1023为知名端口,49152到65535为动态端口。

Figure out what you like. Try to become the best in the world of it.
2014-08-21 11:57
快速回复:网络通信服务端程序问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.022523 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved