//本文在c++ builder 10.3调试通过。
//在以前的文章中介绍了标准的windows socek,本文介绍使用TServerSocket 组件,做服务端。
//1.安装组件
//Component->Install Packages->Add->弹出文件选择框->找到 dclsockets260.bpl->打开->Save
//2.新建窗体项目
//2.1在窗体上放置一个TShape组件(Palette->Addtional->TShape),设置名称为Shape1
//2.2.在窗体上放置一个TSeverSocket组件(Palette->Internet->TServerSocket)
//设置名称为ServerSocket1,设置属性
//设置事件的代码,点击下图右边空白自动产生事件关联的函数(蓝色部分)并且自动生成代码
//3.代码
#include <vcl.h> #pragma hdrstop #include "Unit7.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm7 *Form7; TCustomWinSocket *Socket1 ; //--------------------------------------------------------------------------- __fastcall TForm7::TForm7(TComponent* Owner) ? ? : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm7::FormCreate(TObject *Sender) {?try ?{ServerSocket1->Active=true;//打开 ?} ?catch(Exception &ex) ?{AnsiString str= "启动socket服务失败 "; ? str+= IntToStr(ServerSocket1->Port) ; ? str+=ex.Message; ? OutputDebugStringA(str.c_str()); ?} } //- //--------------------------------------------------------------------------- void __fastcall TForm7::ServerSocket1ClientConnect(TObject *Sender, TCustomWinSocket *Socket)// {Shape1-> Brush->Color = clLime;//连接后绿灯亮 } //--------------------------------------------------------------------------- void __fastcall TForm7::ServerSocket1ClientDisconnect(TObject *Sender, TCustomWinSocket *Socket) {Shape1-> Brush->Color = clBtnFace;//关闭后绿灯灭 } //--------------------------------------------------------------------------- void __fastcall TForm7::ServerSocket1ClientError(TObject *Sender, TCustomWinSocket *Socket, ? ? ? ? ? TErrorEvent ErrorEvent, int &ErrorCode) {OutputDebugStringA("---------------error-----------------------"); ?try ?{AnsiString s="Error:"+AnsiString(ErrorCode); ? if(ErrorCode==10053) ? Socket->Close(); ? ErrorCode=0; ? } ? catch(...){} } //--------------------------------------------------------------------------- void __fastcall TForm7::ServerSocket1ClientRead(TObject *Sender, TCustomWinSocket *Socket)
{try ?{Socket1? ? ? = Socket; ? unsigned char Buf[1024] ; ? byte *p ? ? ? = Buf ?; ? int ?n ? ? ? = Socket->ReceiveBuf(p,1024); ? char bufferOut[1000]="hello"; ? Client1->SendBuf(&bufferOut,sizeof(bufferOut)); ? } ? catch(...) ? {} }
|