The first learning realizes the communication of the WCF WinForm program, the main function is realizes the picture transmission.
Here is the implementation step:
The first step:
First set up a class library project Transferpiclib, Import the reference system.servicemodel that WCF needs, establish the interface Itransferpicservice, establish the class file Transferpicservice implement the Itransferpicservice interface.
Code: Itransferpicservice
Itransferpicserviceusing system;using system.collections.generic;using system.io;using System.Linq;using System.servicemodel;using system.text;using system.threading.tasks;namespace transferpiclib{ [ServiceContract ] public interface Itransferpicservice { [operationcontract]//operation contract Stream Getpic (); [OperationContract] void Sendpic (Stream transferpic); } }
Code: Transferpicservice
Transferpicserviceusing system;using system.collections.generic;using system.io;using System.Linq;using System.Text ; Using System.threading.tasks;namespace transferpiclib{public class Transferpicservice:itransferpicservice { public static Stream Picsource = new MemoryStream (); <summary>///download images from the server to local (the process of uploading and downloading copies)///</summary>//<returns></retur Ns> public Stream Getpic () {MemoryStream ms = new MemoryStream (); Picsource.position = 0;//indicates that the copy Picsource.copyto (MS) starts from the No. 0 bit;//The server copies the stream of the client to a Ms. Position = 0;//Note If missing this code the receiving end will not be able to display the upload picture return ms;//then return to the client;}//<summary>//from the client Upload the image to the server (copy the stream from the client to the stream on the server)///</summary>//<param name= "Transferpic" ></param> public void Sendpic (Stream transferpic) {picsource.position = 0; Transferpic.copyto (PICSOUrce); }}} to use the App. Config profile, you can copy the required parameters directly by creating a template generated by the WCF service class library.
code: App. Config
App.config<?xml version= "1.0" encoding= "Utf-8"?><configuration> <appSettings> <add key= "ASPNET : Usetaskfriendlysynchronizationcontext "value=" true "/> </appSettings> <system.web> <compilation D Ebug= "true"/> </system.web> <!--When you deploy a service library project, you must add the contents of the configuration file to the Host App. Config file. System.Configuration does not support the library's configuration file. -<system.serviceModel> <services> <service name= "Transferpiclib.transferpicservice" > Step Two:Create a console program Transferpichoset, which primarily launches the WCF service. After the project is established, first add the Transferpiclib reference and the using System.ServiceModel reference.
Code: Program
Programusing system;using system.collections.generic;using system.linq;using system.servicemodel;using System.servicemodel.description;using system.text;using system.threading.tasks;using TransferPicLib;namespace Transferpichose{class Program {static void Main (string[] args) {nettcpbinding bind = new NetTcpBinding (); Bind. MaxBufferSize = 214783647; Bind. Transfermode = transfermode.streamed; Bind. MaxReceivedMessageSize = 214783647; Bind. Security.mode = Securitymode.none; Programs that exceed the using range automatically release using (ServiceHost host = new ServiceHost (typeof (Transferpiclib.transferpicservice))) {host.} AddServiceEndpoint (typeof (Itransferpicservice), bind, "net.tcp://localhost:8100/transferpic");//The address is the host address, And the client receive-side address remains consistent if (host. description.behaviors.find<servicemetadatabehavior> () = = null) {Servicemetadatabe Havior behavior = new ServiceMetadataBehavior (); Behavior. Httpgetenabled = true; Behavior. Httpgeturl = new Uri ("http://localhost:8103/transferPic/metadata/"); Host. DESCRIPTION.BEHAVIORS.ADD (behavior); } host. Opened + = delegate {Console.WriteLine ("The picture program has started successfully! "); }; Host. Open (); Console.ReadLine (); } } }}Now if the first step of the configuration file is not a problem, the service can be started, I do the experiment, encountered the address can not find the error, finally found that the port configuration is wrong, by looking at the official demo found to do the WCF program to start Visual Studio needs to start as an administrator. Temporarily do not know why to start with the administrator, but no impact.
Now the service has been completed, the following we can create a picture upload and receive end, here first set up a picture upload project it
Step Three:Create a WinForm project Winformuploaddemo, this form is mainly to implement the selection of pictures, upload image function. The first to add Transferpiclib references and using system.servicemodel references
The interface layout is as follows:
Code:
Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.io;using system.linq;using system.servicemodel;using system.text;using system.threading.tasks;using system.windows.forms;using transferpiclib;namespace winformuploaddemo{public partial class Uploadform:form { String fileName = ""; Public Uploadform () {InitializeComponent (); private void Btnbrowser_click (object sender, EventArgs e) {OpenFileDialog OpenFileDialog = new OpenFileDialog (); if (Openfiledialog.showdialog () ==dialogresult.ok) {fileName = Openfiledialog.filename; Txtpicname.text = FileName; Picturebox1.load (FileName); }else {return; }} private void Btnupload_click (object sender, EventArgs e) {FileStream fs = new FILESTR EAM (FileName, FileMode.Open, FileAccess.Read); Stream sm = new MemoryStream (); Fs. Position = 0; Fs. CopyTo (SM); Upload endpointaddress epaddr = new EndpointAddress ("Net.tcp://localhost:8100/transferpic") after the copy is completed, or you can use IIS as a service NetTcpBinding bind = new nettcpbinding ();//bind mode bind. Maxbufferpoolsize = 2147483647;//Maximum buffered bind. Transfermode = transfermode.streamed;//Transfer mode is a streaming bind. MaxReceivedMessageSize = 2147483647;//defines the maximum length of message received by the server, preventing the file from being too large bind. Security.mode = securitymode.none;//Safe mode is set to no authentication;//Create a factory Itransferpicservice proxy = Channelfactor Y<itransferpicservice>. CreateChannel (Bind, EPADDR); Sm. Position = 0; Proxy. Sendpic (SM);//WCF client calls this method to upload the client SM to the server;}}}At this point, the image selection and upload function is realized. Below we create the receive end program
Fourth Step:The interface is as follows: Add a PictureBox on the form to show the received picture
Remember to add transferpiclib references and using system.servicemodel references
Code:
Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.io;using system.linq;using system.servicemodel;using system.text;using system.threading;using System.threading.tasks;using system.windows.forms;using transferpiclib;namespace WinFormReceiver{public partial Class Receivedform:form {public Receivedform () {InitializeComponent (); } private void Form1_Load (object sender, EventArgs e) {Thread myThread = new Thread (showpic);//Gen Build a thread Mythread.isbackground = true;//set a background thread (to prevent the main program from shutting down, still running) mythread.start ();//Start thread} p ublic void Showpic () {#region As the client, create a WCF client endpointaddress epaddr = new EndpointAddress (" Net.tcp://localhost:8100/transferpic "); NetTcpBinding bind = new nettcpbinding (); Bind. Maxbufferpoolsize = 2147483647; Bind. Transfermode = Transfermode.streamed; Bind. MaxReceivedMessageSize = 2147483647; Bind. Security.mode = Securitymode.none; Create a channel Itransferpicservice proxy = Channelfactory<itransferpicservice>. CreateChannel (Bind, EPADDR); #endregion while (true) {Stream Streamfromserver = proxy. Getpic (); Returns a file stream; MemoryStream ms = new MemoryStream ();//filter laminar flow copy; Ms. Position = 0; Streamfromserver.copyto (MS);//Copy the file stream to MS; Length = = 0) {System.Threading.Thread.Sleep (300);//300 hundred milliseconds execution once; Conti Nue } Bitmap tn = new Bitmap (ms);//Create a bitmap; Turn Ms into a picture; picturebox1.image = TN; System.Threading.Thread.Sleep (300);//300 hundred milliseconds to execute once; Sleep indicates that the current thread has been suspended for the specified time;}}} Here our code is done.Fifth StepTest to launch our project.
Four, run the program.
1. Open the Bin directory in the Transferpichost file, start "TransferPicHost.exe", a console application will pop up the form, and prompt "The picture function has been successfully started!" ”。
2. Start the sending and receiving terminal project program respectively;
(set "Winformclient" or "Winformreceiver" as the startup Project and start the "WinFormReceiver.exe" or "WinFormClient.exe" in the bin directory of another project folder)
Click the Send side "browse button" to select the image, then click on the "Upload button". At this point, you will find that the client uploaded images are displayed on the receiving side of the form. The program ran successfully.
WCF implements the upload image feature