请帮我写一个使用wxWidgets界面库的tcp协议传输文件的程序
时间: 2023-06-06 08:05:40 浏览: 67
好的,我可以帮您写一个使用wxWidgets界面库的tcp协议传输文件的程序。
以下是示例代码:
```c++
#include <wx/wx.h>
#include <wx/socket.h>
#include <iostream>
class MyFrame : public wxFrame {
public:
MyFrame (const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame(NULL, wxID_ANY, title, pos, size),
m_button(NULL) {
wxPanel* panel = new wxPanel(this, wxID_ANY);
wxStaticText* label = new wxStaticText(panel, wxID_ANY,
wxT("请输入文件名:"),
wxPoint(10, 10));
m_textCtrl = new wxTextCtrl(panel, wxID_ANY, wxT(""),
wxPoint(10, 30), wxSize(200, -1),
wxTE_PROCESS_ENTER);
m_button = new wxButton(panel, wxID_ANY, wxT("传输文件"),
wxPoint(10, 60), wxSize(-1, -1));
m_button->Disable();
Connect(m_textCtrl->GetId(), wxEVT_TEXT_ENTER,
wxCommandEventHandler(MyFrame::OnTextEnter));
Connect(m_button->GetId(), wxEVT_BUTTON,
wxCommandEventHandler(MyFrame::OnButtonClicked));
EnableFileTransfer(false);
}
private:
wxTextCtrl* m_textCtrl;
wxButton* m_button;
void OnTextEnter(wxCommandEvent& event) {
EnableFileTransfer(true);
event.Skip();
}
void OnButtonClicked(wxCommandEvent& event) {
// 获取用户输入的文件名
wxString fileName = m_textCtrl->GetValue();
// 创建TCP客户端套接字
wxSocketClient* client = new wxSocketClient(wxSOCKET_WAITALL);
// 连接到服务器
wxIPV4address address(wxT("127.0.0.1"), 12345);
client->Connect(address, false);
// 打开文件
wxFile file(fileName);
if (!file.Exists()) {
wxMessageBox(wxT("文件不存在!"));
return;
}
// 发送文件名和文件大小
wxFileOffset fileSize = file.Length();
wxString header = fileName + wxT(":") + wxString::Format(wxT("%lld"), fileSize) + wxT(":");
client->Write(header.c_str(), header.length());
// 发送文件内容
wxCharBuffer buffer(1024);
wxUint32 bytesRead;
wxUint32 totalBytesSent = 0;
while (totalBytesSent < fileSize) {
bytesRead = file.Read(buffer.data(), 1024);
client->Write(buffer.data(), bytesRead);
totalBytesSent += bytesRead;
}
delete client;
wxMessageBox(wxT("文件传输完成!"));
EnableFileTransfer(false);
}
void EnableFileTransfer(bool enable) {
if (m_button) {
m_button->Enable(enable);
}
}
DECLARE_EVENT_TABLE();
};
BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_CLOSE(MyFrame::OnClose)
END_EVENT_TABLE()
class MyApp : public wxApp {
public:
virtual bool OnInit() {
MyFrame* frame = new MyFrame(wxT("TCP文件传输客户端"), wxPoint(50, 50), wxSize(300, 150));
frame->Show(true);
SetTopWindow(frame);
return true;
}
void OnClose(wxCloseEvent& event) {
// 退出应用程序
ExitMainLoop();
}
};
IMPLEMENT_APP(MyApp);
```
该程序使用 wxWidgets 界面库创建了一个简单的 GUI 界面。用户输入要传输的文件名后,点击“传输文件”按钮,程序会连接到服务器并发送文件。
注意:该程序只能用作客户端,需要与服务端配合使用。同时,本程序仅作为示例演示,请根据您的实际需要进行适当修改。