利用 C++Builder 5.0 內建的 NMSTrm / NMSTrmServ 元件,打造一個「雙向皆可作 Client/Server」的圖片傳輸小工具。雙方啟動程式即可互傳 BMP/JPG 等圖檔,單機雙開亦可測試。
| 元件 | 角色 | 關鍵特性 |
|---|---|---|
| NMSTrm | Client 端資料流發送器 | TCP 連線、發送 TStream、事件驅動 |
| NMSTrmServ | Server 端資料流接收器 | 監聽 TCP 埠、接收 TStream、自動存檔 |
| OpenPictureDialog | 圖片選取對話框 | 支援 BMP/JPG/WMF/EMF/ICO |
| 元件名稱 | 類別 | 關鍵屬性 |
|---|---|---|
| Form1 | TForm | Caption = "發送圖像" |
| Image1 | TImage | 顯示接收圖片 |
| Button1 | TButton | Caption = "發送", OnClick → 發送邏輯 |
| Button2 | TButton | Caption = "顯示", OnClick → 載入 tmp.bmp |
| Button3 | TButton | Caption = "打開", OnClick → OpenPictureDialog |
| Label1 | TLabel | Caption = "遠程主機:" |
| Edit1 | TEdit | 輸入對方 IP/主機名 |
| Edit2 | TEdit | 顯示選取檔案路徑 |
| NMSTrm1 | TNMStrm | Client 發送元件 |
| NMSTrmServ1 | TNMStrmServ | Server 接收元件 |
| OpenPictureDialog1 | TOpenPictureDialog | 圖片選取器 |
| StatusBar1 | TStatusBar | 顯示連線/傳輸狀態 |
void __fastcall TForm1::Button3Click(TObject *Sender) {
if (OpenPictureDialog1->Execute())
Edit2->Text = OpenPictureDialog1->FileName;
}
void __fastcall TForm1::Button1Click(TObject *Sender) {
TFileStream *fs = new TFileStream(OpenPictureDialog1->FileName, fmOpenRead);
try {
NMSTrm1->Host = Edit1->Text; // 目標主機
NMSTrm1->PostIt(fs); // 非同步發送 Stream
} catch (...) {
delete fs; // 異常時手動釋放
}
}
void __fastcall TForm1::NMSTrmServ1MSG(TComponent *Sender,
const AnsiString sFrom, TStream *strm) {
// 覆寫暫存檔
if (FileExists(".\\tmp.bmp")) DeleteFile(".\\tmp.bmp");
TFileStream *fs = new TFileStream(".\\tmp.bmp", fmCreate);
try {
fs->CopyFrom(strm, strm->Size); // 全部寫入
} catch (...) { }
delete fs;
}
void __fastcall TForm1::NMSTrm1Connect(TObject *Sender) {
StatusBar1->SimpleText = "Connected";
}
void __fastcall TForm1::NMSTrm1PacketSent(TObject *Sender) {
StatusBar1->SimpleText = IntToStr(NMSTrm1->BytesRecvd) + " bytes of " +
NMSTrm1->BytesTotal + " sent";
}
void __fastcall TForm1::NMSTrm1ConnectionFailed(TObject *Sender) {
ShowMessage("無法連線到對方");
}
Project1.exe.\\tmp.bmp,點「顯示」即可預覽.\\tmp.bmp,實際應依副檔名/MIME 動態決定。NMSTrm 系列元件雖屬經典,但以「資料流即介面」的設計思想,讓 TCP 檔案傳輸變得極其直觀。理解其事件驅動模型後,遷移至現代網路庫將毫無壓力。快動手試試,體驗「代碼極少、功能即現」的快感吧!