winsock编程-使用Qt,多线程

计算机网络实验坑有点多,感谢同学的帮助。

1.使用Qt creator创建widgets application。

2.在项目中的.pro文件中添加一句

LIBS += -lpthread libwsock32 libws2_32

3.编写界面大致如图所示,然后就能开始代码编写了。

4.main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.setWindowTitle("Web 服务器");
    w.show();
    return a.exec();
}

5. mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "waiting.h"
#include<winsock2.h>
#include <QDebug>
#include<QFile>
#include<QFileDialog>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    if(ui->lineEdit->text()==""||ui->lineEdit_2->text()=="")
    {
        ui->textEdit->append("Warning,请输入IP地址和端口号!");
        return;
    }
    else if(ui->lineEdit_3->text()=="")
    {
        ui->textEdit->append("Warning,请输入文件路径!");
    }
    //验证版本
    int nRc = WSAStartup(0x0101, & wsaData);
    if(nRc)
    {
    //Winsock初始化错误
        return;
    }
    if(wsaData.wVersion != 0x0101)
    {
    //版本支持不够
    //报告错误给用户,清除Winsock,返回
        ui->textEdit->append("版本出现问题!");
        WSACleanup();
        return;
    }
    //创建套接字
    mysocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    ui->textEdit->append("Socket 创建成功.");
    //bind
    sockaddr_in addr;
    addr.sin_family = AF_INET;

    //htons和htonl函数把主机字节顺序转换为网络字节顺序,分别用于//短整型和长整型数据
    addr.sin_port = htons(5050);
    addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

    // LPSOCKADDR类型转换是必须的
    nRc = bind(mysocket, LPSOCKADDR(&addr), sizeof(addr) );
    if(nRc == SOCKET_ERROR)
    {
        ui->textEdit->append("bind error!");
        return;
    }
    ui->textEdit->append("Bind 成功.");
    //listen
    listen(mysocket,10);
    ui->textEdit->append("Listen 成功.");
    //创建新线程
    waiting = new Waiting(mysocket,path);
    //当isMsg触发时即进行操作
    connect(waiting,&Waiting::isMsg,this,[=](QString msg){
        ui->textEdit->append(msg);
    });
    waiting->start();
}

void MainWindow::on_pushButton_2_clicked()
{
    waiting->terminate();
    waiting->quit();
    waiting->wait();
    delete waiting;
    ::closesocket(mysocket);
    ui->textEdit->setText("");
    ui->textEdit->append("Socket clossed.");
}

void MainWindow::on_toolButton_clicked()
{
    path
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Winsock 是 Windows 操作系统提供的用于进行网络编程的 API,而 MFC 是基于 Win32 API 的一个 C++ 类库,用于快速开发 Windows 程序。在 MFC 中使用 Winsock 进行多线编程,可以实现网络通信的并发处理。 下面是一个使用 MFC 和 Winsock 实现的简单的多线程网络程序的示例: ```cpp // MySocket.h class CMySocket : public CSocket { public: CMySocket(); virtual ~CMySocket(); void SetParent(CWnd* pParentWnd); void SetPort(UINT nPort); void SetIPAddress(LPCTSTR lpszIPAddress); protected: virtual void OnReceive(int nErrorCode); private: CWnd* m_pParentWnd; UINT m_nPort; CString m_strIPAddress; }; // MySocket.cpp CMySocket::CMySocket() { m_pParentWnd = NULL; m_nPort = 0; m_strIPAddress.Empty(); } CMySocket::~CMySocket() { } void CMySocket::SetParent(CWnd* pParentWnd) { m_pParentWnd = pParentWnd; } void CMySocket::SetPort(UINT nPort) { m_nPort = nPort; } void CMySocket::SetIPAddress(LPCTSTR lpszIPAddress) { m_strIPAddress = lpszIPAddress; } void CMySocket::OnReceive(int nErrorCode) { if (nErrorCode == 0) { char szBuffer[1024]; int nBytes = Receive(szBuffer, sizeof(szBuffer)); if (nBytes > 0) { // 处理接收到的数据 CString strData(szBuffer, nBytes); m_pParentWnd->SendMessage(WM_MY_SOCKET_RECEIVE, (WPARAM)this, (LPARAM)&strData); } } CSocket::OnReceive(nErrorCode); } // MyThread.h class CMyThread : public CWinThread { public: CMyThread(); virtual ~CMyThread(); void SetParent(CWnd* pParentWnd); void SetPort(UINT nPort); protected: virtual BOOL InitInstance(); virtual int ExitInstance(); private: CWnd* m_pParentWnd; UINT m_nPort; }; // MyThread.cpp CMyThread::CMyThread() { m_pParentWnd = NULL; m_nPort = 0; } CMyThread::~CMyThread() { } void CMyThread::SetParent(CWnd* pParentWnd) { m_pParentWnd = pParentWnd; } void CMyThread::SetPort(UINT nPort) { m_nPort = nPort; } BOOL CMyThread::InitInstance() { // 创建服务器端套接字 CMySocket socketServer; socketServer.SetParent(m_pParentWnd); socketServer.Create(m_nPort); socketServer.Listen(); while (TRUE) { // 等待客户端连接 CMySocket* pSocketClient = new CMySocket; pSocketClient->SetParent(m_pParentWnd); socketServer.Accept(*pSocketClient); // 创建客户端线程 CMyThread* pThreadClient = new CMyThread; pThreadClient->SetParent(m_pParentWnd); pThreadClient->SetPort(0); pThreadClient->m_bAutoDelete = TRUE; pThreadClient->CreateThread(); } return TRUE; } int CMyThread::ExitInstance() { return CWinThread::ExitInstance(); } // MyDialog.h class CMyDialog : public CDialog { public: CMyDialog(CWnd* pParent = NULL); virtual ~CMyDialog(); enum { IDD = IDD_MY_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); virtual BOOL OnInitDialog(); afx_msg void OnBtnStart(); afx_msg void OnBtnStop(); afx_msg LRESULT OnSocketReceive(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() private: CMyThread* m_pThreadServer; CList<CMySocket*, CMySocket*> m_listSocketClient; }; // MyDialog.cpp BEGIN_MESSAGE_MAP(CMyDialog, CDialog) ON_BN_CLICKED(IDC_BTN_START, &CMyDialog::OnBtnStart) ON_BN_CLICKED(IDC_BTN_STOP, &CMyDialog::OnBtnStop) ON_MESSAGE(WM_MY_SOCKET_RECEIVE, &CMyDialog::OnSocketReceive) END_MESSAGE_MAP() CMyDialog::CMyDialog(CWnd* pParent /*=NULL*/) : CDialog(CMyDialog::IDD, pParent) { m_pThreadServer = NULL; } CMyDialog::~CMyDialog() { } void CMyDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BOOL CMyDialog::OnInitDialog() { CDialog::OnInitDialog(); return TRUE; } void CMyDialog::OnBtnStart() { // 创建服务器线程 m_pThreadServer = new CMyThread; m_pThreadServer->SetParent(this); m_pThreadServer->SetPort(12345); m_pThreadServer->m_bAutoDelete = TRUE; m_pThreadServer->CreateThread(); } void CMyDialog::OnBtnStop() { // 关闭服务器线程和所有客户端套接字 if (m_pThreadServer != NULL) { m_pThreadServer->PostThreadMessage(WM_QUIT, 0, 0); m_pThreadServer = NULL; } POSITION pos = m_listSocketClient.GetHeadPosition(); while (pos != NULL) { CMySocket* pSocket = m_listSocketClient.GetNext(pos); pSocket->Close(); delete pSocket; } m_listSocketClient.RemoveAll(); } LRESULT CMyDialog::OnSocketReceive(WPARAM wParam, LPARAM lParam) { // 处理客户端套接字的接收事件 CMySocket* pSocket = (CMySocket*)wParam; CString* pstrData = (CString*)lParam; // 发送数据到客户端 pSocket->Send(pstrData->GetBuffer(), pstrData->GetLength()); return 0; } ``` 在上面的示例中,`CMySocket` 类继承自 `CSocket`,重载了 `OnReceive` 方法,处理套接字的接收事件,将接收到的数据发送给主窗口。`CMyThread` 类继承自 `CWinThread`,重载了 `InitInstance` 方法,创建服务器端套接字,并循环接收客户端连接,每次接收到客户端连接时创建一个客户端线程。`CMyDialog` 类继承自 `CDialog`,包含了开始和停止按钮,点击开始按钮创建服务器线程,点击停止按钮关闭服务器线程和所有客户端套接字,同时处理客户端套接字的接收事件,将接收到的数据发送回客户端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值