//--------------------------------------------------------------------------- void __fastcall TWSocketThread::Execute() { // Let's the user know what we are doing printf("Connecting to server '" ServerHostName "' on port '" ServerPort "'\n"); // Create the TWSocket we will use to commicate with the server FWSocket = new TWSocket((void *)NULL); // Assign the event handler for the TWSocket events we care of FWSocket->OnDataAvailable = FWSocketDataAvailable; FWSocket->OnSessionClosed = FWSocketSessionClosed; FWSocket->OnSessionConnected = FWSocketSessionConnected; // Connect to the server FWSocket->Addr = ServerHostName; FWSocket->Port = ServerPort; FWSocket->Proto = "tcp"; FWSocket->Connect(); // Let the TWSocket component makes his work FWSocket->MessageLoop(); // We are done, destroy the objects we created delete FWSocket; }
//--------------------------------------------------------------------------- // Event handler for datavailable. Called each time some data is received void __fastcall TClientForm::SocketDataAvailable(TObject *Sender, WORD Error) { int Len; char Buffer[256]; TWSocket *Socket; int I; AnsiString Msg; Socket = (TWSocket *)Sender; Len = Socket->Receive(Buffer, sizeof(Buffer)); if (Len == 0) // Remote has closed Display("\r\n**** Remote has closed ****\r\n"); else if (Len < 0) { // An error has occured if (Socket->LastError != WSAEWOULDBLOCK) { Msg = "\r\n**** ERROR: " + IntToStr(Socket->LastError) + " ****\r\n"; Display(&Msg); } } else { Buffer[Len] = 0; Display(Buffer); for (I = 0; Buffer[I]; I++) ProcessChar(Buffer[I]); } }
//--------------------------------------------------------------------------- // This event handler is called by the TWSocket when some data has been // received by the lower level. void __fastcall TWSocketThread::FWSocketDataAvailable(TObject *Sender, WORD Error) { int Len; // Get the received data Len = FWSocket->Receive(FRcvBuf, sizeof(FRcvBuf) - 1); if (Len <= 0) return; // Add a terminating nul byte to allow display using standard I/O FRcvBuf[Len] = 0; printf("%s", FRcvBuf); }
//--------------------------------------------------------------------------- // This event handler is called by TWSocket when the connection is broken void __fastcall TWSocketThread::FWSocketSessionClosed(TObject *Sender, WORD Error) { printf("Server has diconnected\n"); FWSocket->Close(); }