Delphi tserversocket and tclientsocket implement file transfer code

Source: Internet
Author: User

Delphi tserversocket and tclientsocket implement File TransferCode

1. Create two engineering servers and clients,

Put the tserversocket and tclientsocket controls, demo, and edit controls respectively.

2. SetTserversocket name is SS, servertype is stnonblocking, tclientsocket name is CS, clienttype is ctnonblocking, indicating asynchronous read/write information. Note that the clienttype and servertype must be consistent. If it is ctblocking, it indicates synchronous read/write information.

 

3. Sequence diagram of files transmitted by socket

A) client --> server mp_query

B) server --> client mp_accept

C) client --> server mp_fileproperty

D) server --> client mp_nextwillbedata

E) client --> server mp_nextwillbedata

F) server --> client mp_data

G) client --> server sends data

H) The server receives and processes data.

I) client --> server mp_end ends

4. client code

  Unit unitclient; Interface Useswindows, messages, sysutils, classes, graphics, controls, forms, dialogs, scktcomp, stdctrls, buttons, extctrls, comctrls; const // Set the Protocol identifier  // Indicates the file name to be sent Mp_query = 'aaaaa '; // Indicates that the server refuses to receive the message Mp_refuse = 'bbbbbb '; // Indicates that the server agrees to receive the file Mp_accept = 'ccccc '; // Mark the data to be transmitted Mp_nextwillbedata = 'ddddd '; // Indicates that the server is preparing to receive data Mp_data = 'eeeee '; // Indicates that the client has canceled this sending operation Mp_abort = 'ffffff '; // The flag has been sent Mp_end = 'iiiiiii '; // Indicates the length of the file to be sent. Mp_fileproperty = 'jjjjj '; // Specify the size of each sent packet Ibytepersend = 1024; typetform1 = Class (Tform) opendialog1: topendialog; CS: tclientsocket; Panel1: tpanel; btnsendfile: enabled; edtipaddress: tedit; memo1: tmemo; edthostname: tedit; rb: enabled; Rb2: enabled; probar: tprogressbar; btncancel: plugin; btnexit: plugin; procedure invoke (Sender: tobject); Procedure csread (Sender: tobject; socket: plugin); Procedure formcreate (Sender: tobject ); procedure btncancelclick (Sender: tobject); Procedure btnexitclick (Sender: tobject ); Private      // Define a data stream for sending files Fssend: tfilestream; // Set the start position Tstart: Boolean; // Identify the current time Tickcount: longword; {private Declarations} Public {Public declarations} end; varform1: tform1; implementation {$ R *. DFM} // Send a file Procedure tform1.btnsendfileclick (Sender: tobject); begin // Close the socket connection CS. close; // Initialize process entries Probar. Position: = 0; If Rb1.checked thenbegin CS. HOST: = ''; // Specify the IP address of the host to be connected CS. Address: = edtipaddress. Text; End Else  // Specify the host name to be connected CS. HOST: = edthostname. text; // Port Number of the host to be connected CS. Port: = 2000; // Open the socket connection CS. open;// Click send confirmation.  If Opendialog1.execute thenbegin // Send a connection request CS. Socket. sendtext (mp_query + opendialog1.filename); end; // The client receives information from the server Procedure tform1.csread (Sender: tobject; socket: tcustomwinsocket); varmsgrecv: String ; Bufsend: pointer; ilength: integer; begin // Obtain the information sent from the client Msgrecv: = socket. receivetext; // Obtain the first five digits to obtain the Protocol identifier. Msgrecv: = copy (msgrecv, 1, 5 ); // The rejected message is received.  If Msgrecv = mp_refuse then memo1.lines. Add ('Connection request rejected! ')// Receive confirmation message  Else   If Msgrecv = mp_accept thenbegin // Create a file stream for the file to be sent Fssend: = tfilestream. Create (opendialog1.filename, fmopenread); tstart: = false; // Progress bar display Probar. MAX: = fssend. size; memo1.lines. Add ('start sending! '); // Obtain the sending Start Time Tickcount: = gettickcount; // Create a file stream and send the file length. Socket. sendtext (mp_fileproperty + inttostr (trunc (fssend. Size/ibytepersend) + 1); End Else   If Msgrecv = mp_nextwillbedata thenbegin// Notify the receiving end that data will be transmitted. Socket. sendtext (mp_nextwillbedata); End Else   If Msgrecv = mp_data thenbegin // Receive the confirmation message and start sending data.      If Not tstart then begin memo1.lines. Add ('sending data... '); tstart: = true; end; // There is still data not sent.      If Fssend. Position <fssend. Size-1 then begin ilength: = fssend. Size-1-fsSend.Position; // Send data in Segments        If Ilength> ibytepersend then ilength: = ibytepersend; getmem (bufsend, ilength + 1 );Try          // Read file stream data Fssend. Read (bufsend ^, ilength ); // Send data with the length of ilength Socket. sendbuf (bufsend ^, ilength ); // Progress bar display Probar. Position: = fssend. position; Finally          // Release the memory Freemem (bufsend, ilength + 1); end; // Sent End Else Begin // Notify the host that file transfer is complete. Socket. sendtext (mp_end); memo1.lines. Add ('sending completed! '); // Obtain the sending duration Memo1.lines. Add ('sending time consumed '+ inttostr (gettickcount-tickcount) + 'millisecond'); fssend. Free; end; // Cancel the File Sending Process End Else   If Msgrecv = mp_abort thenbegin memo1.lines. Add ('abort! '); // File transfer canceled Fssend. Free; end; Procedure tform1.formcreate (Sender: tobject); beginmemo1.clear; end; // Cancel Procedure tform1.btncancelclick (Sender: tobject); begin // Cancel the File Sending Process CS. Socket. sendtext (mp_abort); end; Procedure tform1.btnexitclick (Sender: tobject); beginform1.close; end.

5. server code

  Unit Unitserver; Interface  Uses Windows, messages, sysutils, classes, graphics, controls, forms, dialogs, stdctrls, buttons, scktcomp, extctrls; const // Set the Protocol identifier  // Indicates the file name to be sent Mp_query = 'aaaaa '; // Indicates that the server refuses to receive the message Mp_refuse = 'bbbbbb '; // Indicates that the server agrees to receive the file Mp_accept = 'ccccc '; // Mark the data to be transmitted Mp_nextwillbedata = 'ddddd '; // Indicates that the server is preparing to receive data Mp_data = 'eeeee '; // Indicates that the client has canceled this sending operation Mp_abort = 'ffffff ';// The flag has been sent Mp_end = 'iiiiiii '; // Indicates the length of the file to be sent. Mp_fileproperty = 'jjjjj '; // Specify the size of each sent packet Ibytepersend = 1024; Type Tform1 = Class (tform) savedialog1: tsavedialog; SS: tserversocket; memo1: tmemo; Procedure Ssclientread (Sender: tobject; socket: tcustomwinsocket ); Procedure Formcreate (Sender: tobject ); Procedure Formdestroy (Sender: tobject); Private // Define the data stream of A received File Fsrecv: tfilestream; // Set the start position Tstart: Boolean; // Identify the current time Tickcount: longword; {private Declarations} public {public declarations} End ; VaR Form1: tform1; Implementation {$ R *. DFM} // The server receives information from the client.  Procedure Tform1.ssclientread (Sender: tobject; socket: tcustomwinsocket ); VaR MSGR, thefilename: String ; Bufrecv: pointer; ilength: integer; Begin  // The length of the received data Ilength: = socket. cancelength;// Open up a new memory to save the received data Getmem (bufrecv, ilength); try // Receive data Socket. receivebuf (bufrecv ^, ilength ); // Save the received data in MSGR as a string MSGR: = strpas (pchar (bufrecv )); // Take the first five characters MSGR: = copy (MSGR, 1, 5 ); If MSGR = mp_query Then      Begin        // Remove spaces and control characters before and after the string MSGR: = trim (strpas (pchar (bufrecv ))); // The string after 5th characters is the file name Thefilename: = extractfilename (copy (MSGR, 6, length (MSGR); savedialog1.title: = 'select or enter the name of the file to which the received data is saved: '; savedialog1.filename: = thefilename; // Click OK to save        If Savedialog1.execute Then        Begin          // Create a file stream for the file to be saved Fsrecv: = tfilestream. Create (savedialog1.filename, fmcreate ); // If you agree to receive data. Memo1.lines. Add ('starts receiving! '); Tickcount: = gettickcount; // Send the information that agrees to receive the file Socket. sendtext (mp_accept); tstart: = false; End        Else         // Send information about the rejected File Socket. sendtext (mp_refuse ); End      Else   If MSGR = mp_fileproperty Then      Begin        // The length of the received file and indicates that the host can receive data Socket. sendtext (mp_nextwillbedata ); End      Else   If MSGR = mp_nextwillbedata Then      Begin        // The sender is required to send data Socket. sendtext (mp_data );End   Else   If MSGR = mp_end Then      Begin Memo1.lines. Add ('file transfer completed! '); Memo1.lines. Add ('receipt time consumed' + inttostr (gettickcount-tickcount) + 'millisecond '); fsrecv. Free; End      // Receives the file transfer cancellation message      Else   If MSGR = mp_abort Then          Begin Memo1.lines. Add ('mp _ abort '); socket. sendtext (mp_abort); fsrecv. Free; End    Else      Begin        If   Not Tstart Then        Begin Memo1.lines. Add ('receive data... '); tstart: = true; End ; // Write the Received Buffer data to a file Fsrecv. writebuffer (bufrecv ^, ilength ); // Notify the client to continue sending data Socket. sendtext (mp_data ); End ; Finally // Release the memory Freemem (bufrecv, ilength ); End ;End ; Procedure Tform1.formcreate (Sender: tobject ); Begin Memo1.clear; // Set the listening port Ss.port: = 2000; // Start listening SS. open; End ; Procedure Tform1.formdestroy (Sender: tobject ); Begin SS. close; End ; End .

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.