Implementing Web Services and its client (non-web) application calls related asynchronous execution Web method

xiaoxiao2021-03-06  39

Implementing Web Services and its client (non-web) application calls related asynchronous execution Web method

The client application of this article does not include ASP.NET web applications!

This article assumes URL: http://localhost/mywebservices/updownload.asmx

A total of 4 program files (Web.config will not be described)

Server Side:

The "asynchronous" mentioned in the title is actually not special in the server-side program, which is mainly implemented by the client application asynchronous calls related Web Method!

1. Updownload.asmx, a web shared directory in IIS, the code is as follows, only one sentence:

<% @ Webservice Language = "C #" codebehind = "Updownload.asmx.cs" class = "service1"%>

2. Updownload.asmx.cs, ie: updownload.asmx's codeBehind, under the bin subdirectory of a web shared directory of IIS, the code is as follows:

/ *

This file is located in the bin subdirectory of the web shared directory, compiles the following command line: CSC / T: library updownload.asmx.cs

* / using system.diagnostics; using system.web.services; using system.io; using system;

Public class service1: system.web.services.Webservice {[WebMethod] public string helloworld () {return "Hello World";

// From the Web Method itself, it can't see "synchronization" or "asynchronous" [WebMethod "[WebMethod (Description =" In order to support multi-point sequential asynchronous upload files, this method must be pre-invoked by the client to generate a specified FileName in the server. And Length size blank file predetermined space! Recommended client synchronization call ")] Public String CreateBLankFile (String filename, INT longth) // Recommended by the client synchronous call {filestream fs = new filestream (server.mappath (". ") "//" FileName, FileMode.Openorcreate, FileAccess.Readwrite, Fileshare.none; fs.write (New Byte [Length], 0, Length); fs.close (); fs = null; returnaMe " (" Length ") blank file has been created! ";

[WebMethod (Description = "provides a method for a complete uploading full file! Recommended client synchronization call")] Public string UploadFileBytes (byte [】 Bytes, String FileName) {Return UploadFilechunkBytes (bytes, 0, filename);}

[WebMethod (Description = "provides a FileName file block that starts only by the POSITION position once, bytes bytes bytes, the BYTES byte is stored in the corresponding byte position of the corresponding file of the server.") As long as a Position parameter is provided, the rest of the rest of the client calls the method, it is easy to achieve the purpose! Public string UploadFilechunkBytes (Byte [] Bytes, int position, string filename) {Try {filestream fs = new filestream (server) . Mappath (".") "//" filename, filemode.openorcreate, fileaccess.readwrite, fileshare.readwrite; // This bytes byte should be written to the server-side byte fs starting from the Position .Position = position; fs.write (bytes, 0, bytes.length; fs.close (); fs = null; returna filename file block: Location [" Position ", " (Position Bytes. Length) "] Size (" bytes.length ") upload success!";} Catch (exception e) {return E.MESSAGE;}} [WebMethod] public Byte [] Downloadfilebytes (String FileName) {IF (file "{ix .Exists (filename)) {Try {filestream fs = file.openread (filename); int i = (int) fs.length; byte [] ba = new byte [i]; fs.read (ba, 0, i) Fs.close (); return ba;} catch {return new byte [0];}} else {r Eturn New Byte [0];}}}

/ / =========================================================================================================================================================================================== =====================================================================================================================================================

Client Side: 3. UpdownloadProxy.cs: This file is generated by the following command to generate% Visual Studio .NET 2003 installation directory% / sdk / v1.1 / bin / wsdl.exe specific command line as follows: WSDL.EXE / L: CS /out:updownloadProxy.cs http://localhost/mywebservices/Updownload.asmx? WSDL generated local client proxy class has generated a method of asynchronous and synchronous execution, for example: public string helloworld () {} Public system.iasyncResult beginhelloworld (...) {} public string endhelloWorld (...) {} The following is the complete UPDownloadProxy.cs code generated by the command line, no modification: / *

Generate UpdownloadProxy.dll: CSC / T: Library UpdownloadProxy.cs by executing the following command line

* /

/ / -------------------------------------------------------------------------------------------- ------------------------------ // // this code WAS generated by a Tool.// runtime version: 1.1.4322.573/// CHANGES TO THIS FILE MAY CAUSE INCORRECT Behavior and Will Be Lost IF // The code is regenerated> // --------------- -------------------------------------------------- -------------

// // This source code is automatically generated by WSDL, Version = 1.1.4322.573. // Using system.diagnostics; using system.xml.serialization; using system; using system.web.services.protocols; using system.componentmodel; using system.Web.Services;

/// [System.Diagnostics.DebuggerStepThroughAttribute ()] [System.ComponentModel.DesignerCategoryAttribute ( "code")] [System.Web.Services.WebServiceBindingAttribute (Name = "Service1Soap", Namespace = "http: // tempuri.org/")]public class Service1: System.Web.Services.Protocols.SoapHttpClientProtocol {/// public Service1 () {this.Url = "http: //localhost/MyWebServices/updownload.asmx" ;} /// [System.Web.Services.Protocols.SoapDocumentMethodAttribute ( "http://tempuri.org/HelloWorld", RequestNamespace = "http://tempuri.org/", ResponseNamespace = "http: //tempuri.org/ ", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string HelloWorld () {object [] results = this. Invoke ("HelloWorld", New Object [0]); Return (Results [0]));} /// Public System.iasyncResult BeginHelloWorld (System.AssyncCallback Callback, Object t asyncState) {return this.BeginInvoke ( "HelloWorld", new object [0], callback, asyncState);} /// public string EndHelloWorld (System.IAsyncResult asyncResult) {object [] results = this.EndInvoke (asyncResult); return ((string) (results [0]));} /// [System.Web.Services.Protocols.SoapDocumentMethodAttribute ( "http://tempuri.org/CreateBlankFile", RequestNamespace = "http://tempuri.org/", responsenamespace = "http://tempuri.org/", USE =

System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string CreateBlankFile (string FileName, int Length) {object [] results = this.Invoke ( "CreateBlankFile" , new object [] {FileName, Length}); return ((string) (results [0]));} /// public System.IAsyncResult BeginCreateBlankFile (string FileName, int Length, System.AsyncCallback callback, object asyncState) {return this.BeginInvoke ( "CreateBlankFile", new object [] {FileName, Length}, callback, asyncState);} /// public string EndCreateBlankFile (System.IAsyncResult asyncResult) {object [] results = this.EndInvoke (asyncResult); return ((string) (results [0]));} /// [System.Web.Services.Protocols.SoapDocumentMethodAttribute ( "http://tempuri.org/UploadFileBytes ", RequestNamespace = "Http://tempuri.org/", ResponseNamespace = "http://tempuri.org/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle .Wrapped)] public string UploadFileBytes ([System.Xml.Serialization.XmlElementAttribute (DataType = "base64Binary")] System.Byte [] Bytes, string FileName) {object [] results = this.Invoke ( "UploadFileBytes", new object [] {Bytes, filename}; return (string) (Results [0]));} ///

public System.IAsyncResult BeginUploadFileBytes (System.Byte [] Bytes, string FileName, System.AsyncCallback callback, object asyncState) {return this.BeginInvoke ( "UploadFileBytes", new object [] {Bytes, FileName}, callback, asyncState);} /// public string enduploadFilebytes (System.IasyncResult asyncRESULT) {Object [] results = this.endinvoke (asyncRESULT); RETURN (String));} /// [System.Web.Services.Protocols.SoapDocumentMethodAttribute ( "http://tempuri.org/UploadFileChunkBytes", RequestNamespace = "http://tempuri.org/", ResponseNamespace = "http://tempuri.org/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string UploadFileChunkBytes ([System.Xml.Serialization.XmlElementAttribute (DataType = "base64Binary")] System. Byte [] bytes, int position, string filename {Object [] results = this.Invoke ( "UploadFileChunkBytes", new object [] {Bytes, Position, FileName}); return ((string) (results [0]));} /// public System.IAsyncResult BeginUploadFileChunkBytes ( System.Byte [] Bytes, int Position, string FileName, System.AsyncCallback callback, object asyncState) {return this.BeginInvoke ( "UploadFileChunkBytes", new object [] {Bytes, Position, FileName}, callback, asyncState);} / //

public string EndUploadFileChunkBytes (System.IAsyncResult asyncResult) {object [] results = this.EndInvoke (asyncResult); return ((string) (results [0]));} /// [System.Web.Services. Protocols.SoapDocumentMethodAttribute ( "http://tempuri.org/DownloadFileBytes", RequestNamespace = "http://tempuri.org/", ResponseNamespace "http://tempuri.org/" =, Use = System.Web.Services. Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] [return: System.Xml.Serialization.XmlElementAttribute (DataType = "base64Binary")] public System.Byte [] DownloadFileBytes (string FileName) {Object [] results = this.invoke ("Downloadfilebytes", new object [] {filename}); Return ((System.byte []) (Results [0]));} /// public system . IdentyncResult BegindownloadFileBytes (String FileName, System.AssyncCallback Callback, Object AsyncState) {Return this.beginInvoke ("DownloadfilebyT es ", new object [] {FileName}, callback, asyncState);} /// public System.Byte [] EndDownloadFileBytes (System.IAsyncResult asyncResult) {object [] results = this.EndInvoke (asyncResult); Return ((System.byte []) (Results [0]));}}

/ / =========================================================================================================================================================================================== ======================== 4. UpdownloadClient.cs: This program is the core code that really implements file block multi-point asynchronous upload: / *

Compile by performing the following command line: CSC UpdownloadClient.cs /R:UpdownloadProxy.dll

* / using system; using system.io;

Public class class1 {static void main (String [] args) {// Download (ServersidePath, ClientSidePath) Download (@ "e: /test.jpg", @ "f: /test_local.jpg"); System.Console.writeline ("Down End");

System.console.writeline ("Synchronous Up File Exec ..."); UPLOADFILE (@ "E: /NorthWind.mdb"); System.Console.writeline (Synchronous Up File End / N ");

System.console.writeline ("Asynchronous Up Chunks Exec ..."; UPLOADFILECHUNKS (@ "e: /test.rar", 64); system.console.readline ();

public static void UploadFile (string LocalFileName) {Service1 xx = new Service1 (); FileStream fs = new FileStream (LocalFileName, FileMode.Open); // Client Side Path byte [] buffer = new byte [fs.Length]; fs. READ (Buffer, 0, Buffer.Length); // Call the "Synchronous Execute" Local Web Sevices Agent class, equivalent to synchronous calling Web method! Xx.uploadFileBytes (buffer, system.io.path.getFileName (LocalFileName ));

/ / Specify the path to the local file to be uploaded, and each upload file block size public static void uploadfilechunks (String LocalFileName, int chunksize) {service1 xx = new service1 (); string filename = system.io.path.GetFileName LocalFileName);

FileStream Fs = New FileStream (LocalFileName, FileMode.Open); // Client Side Path // FS = file.openread (localfilename);

INT r = (int) fs.lend; // Used to record the number of bytes that remain in the remaining, the initial value is the size of the file

// Call the method of "synchronous execution", the method of the local Web Sevices agent class, which is equivalent to the web method! // predetermined server-side space XX.CreateBlankFile (filename, r); int size = chunksize * 1024; int K = 0 ; // Used to record number i that has been uploaded by I ; // is used to record the number of file blocks that are uploaded, while (r> = size) {byte [] buffer = new byte [size]; fs.read (buffer, 0 , buffer.Length; // Call the "asynchronous execution" method method, equivalent to calling the web method! // This buffer byte to write to the server side corresponding file starting from position = K Byte XX.BeginuploadFilechunkBytes (Buffer, K, FileName, New AsyncCallback (UploadFilechunkCallback), XX); K = Size; R - = size; i ;} if (r> 0) // Remaining zero head {byte [] Buffer = new byte [r]; fs.read (buffer, 0, buffer.Length); // Call the "asynchronous execution" method method, equivalent to calling Web method! // This buffer Bytes should be written to bytes starting from position = K from Position = K from Position = K, I ;} fs.close ();

}

Private static int i = -1; // Used to record the number of file blocks uploaded

private static void UploadFileChunkCallback (IAsyncResult ar) {Service1 x = (Service1) ar.AsyncState; Console.WriteLine (x.EndUploadFileChunkBytes (ar)); if (--i == 0) {Console.WriteLine ( "Asynchronous up all chunks End ");}}

Public Static Void Download (String LocalFileName) {service1 xx = new service1 (); byte [] ba = xx.downloadfilebytes; // server side path

FileStream Fs = New FileStream (LocalFileName, FileMode.create); // Client Side Path Fs.write (ba, 0, ba.length); fs.close ();}

转载请注明原文地址:https://www.9cbs.com/read-81846.html

New Post(0)