Function introduction:
It mainly uses the WCF framework to implement the basic functions of uploading images from the client to the server and displaying images on the server.
1. Create two Windows form applications: "WinFormClient" (client, Sender) and "WinFormReceiver" (acceptor)
1. design the FormClient (sending form) interface. A TextBox and two buttons are added to a panel container, and a PictureBox control is added below (used to browse the pictures before uploading ).
Then add the background code under the browser button to implement the client browsing function.
View Code
String fileName = ""; // defines a global variable;
// Browse and select the uploaded content
Private void btnBrowser_Click (object sender, EventArgs e)
{
// String fileName = ""; // defines a field for obtaining the uploaded file name;
OpenFileDialog openFileDialog = new OpenFileDialog (); // create an OpenFileDialog object to open a file
If (openFileDialog. ShowDialog () = DialogResult. OK) // if the OK button is selected in the open file dialog box, it is true. Execute the content in braces
{
FileName = openFileDialog. FileName;
TxtPicName. Text = fileName; // display the file name in textBox
PictureBox1.Load (fileName); // display the image in the pictuBox Client
}
Else
Return; // if the file is not selected, return;
}
Set WinFomClient as the startup project and run
After you select an image, the image will be displayed in the form of the sender for the sender to browse. If you need to change the uploaded image, you can reselect the image and the image will be overwritten. (The upload function will be implemented below)
2. You only need to add a PictureBox control to the form of the FormReceiver receiver to display the pictures uploaded by the client.
2. Add two class libraries in the solution: ITransferPic (Interface), TransferPic (inherited Interface), and TransferPicHost (Host Program) of a console application );
This instance uses "self-hosted host" instead of "IIS host ".
1. ITransferPic
(1) Add reference: using System. ServiceModel; using System. IO;
(2) create an "ITransferPicService" Interface
View Code
[ServiceContract]
Public interface ITransferPicService
{
[OperationContract] // operation contract
Stream GetPic ();
[OperationContract]
Void SendPic (Stream transferPic );
}
2. TransferPic
(1) Add reference: using ITransferPic; using System. IO;
(2) create a "TransferPicService" class, inherit the interface "ITransferPicService" and implement this interface;
View Code
Public class TransferPicService: ITransferPicService
{
Public static Stream PicSource = new MemoryStream ();
/// <Summary>
/// Download the image from the server to the local device (both upload and download are copies)
/// </Summary>
/// <Returns> </returns>
Public Stream GetPic ()
{
MemoryStream MS = new MemoryStream ();
PicSource. Position = 0; // indicates that the copy starts from 0th bits.
PicSource. CopyTo (MS); // The server copies the Stream of the Client
Ms. Position = 0; // note that if this code is missing, the receiving end cannot display the uploaded image.
Return MS; // then return the client;
}
/// <Summary>
/// Upload images from the client to the server (copy the Stream of the client to the Stream of the server)
/// </Summary>
/// <Param name = "transferPic"> </param>
Public void SendPic (Stream transferPic)
{
PicSource. Position = 0;
TransferPic. CopyTo (PicSource );
}
}
3. TransferPicHose
Self-hosted HOST: using the Open () and Close () methods provided by ServiceHost <T> provided by WCF, developers can easily apply applications on the console, Windows applications, and ASP.. NET application. Regardless of the application in the Self-hosted environment, the methods for hosting services are essentially the same. For example, the code used in this instance:
Add reference:
Using System. ServiceModel;
Using ITransferPic;
Using System. ServiceModel. Description;
View Code
Class Program
{
Static void Main (string [] args)
{
NetTcpBinding bind = new NetTcpBinding ();
Bind. MaxBufferSize = 214783647;
Bind. TransferMode = TransferMode. Streamed;
Bind. maxcompute edmessagesize = 214783647;
Bind. Security. Mode = SecurityMode. None;
// Programs beyond the using range will be automatically released
Using (ServiceHost host = new ServiceHost (typeof (TransferPic. TransferPicService )))
{
Host. AddServiceEndpoint (typeof (ITransferPicService), bind, "net. tcp: // localhost: 9600/transferPic"); // The address is the host address, which is consistent with the client receiver address.
If (host. Description. Behaviors. Find <ServiceMetadataBehavior> () = null)
{
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior ();
Behavior. HttpGetEnabled = true;
Behavior. HttpGetUrl = new Uri ("http: // localhost: 9603/transferPic/metadata /");
Host. Description. Behaviors. Add (behavior );
}
Host. Opened + = delegate {Console. WriteLine ("the image program has been started successfully! ");};
Host. Open ();
Console. ReadLine ();
}
}
}
3. Implement upload.
1. WinFormClient background upload button section;
Add reference:
Using System. IO;
Using System. ServiceModel;
Using ITransferPic;
View Code
// Execute the upload function
Private void btnUpload_Click (object sender, EventArgs e)
{
// PictureBox1.Load (fileName );
// Read the stream and upload the file to the server
FileStream fs = new FileStream (fileName, FileMode. Open, FileAccess. Read); // create a file and put the file in the file stream;
Stream sm = new MemoryStream (); // create a filter layer Stream to copy files from 0th bits to sm
Fs. Position = 0; // get or set the current Position of the stream
Fs. CopyTo (sm );
// Upload after the copy is completed
EndpointAddress epAddr = new EndpointAddress ("net. tcp: // localhost: 9600/transferPic"); // you can also use IIS for service.
NetTcpBinding bind = new NetTcpBinding (); // binding method
Bind. MaxBufferPoolSize = 2147483647; // maximum buffer size
Bind. TransferMode = TransferMode. Streamed; // The transmission mode is stream processing.
Bind. maxcompute edmessagesize = 2147483647; // defines the maximum length of the Message received by the server to prevent files from being too large.
Bind. Security. Mode = SecurityMode. None; // The Security Mode is set to not verified;
// Create a factory
ITransferPicService proxy = ChannelFactory <ITransferPicService>. CreateChannel (bind, epAddr );
Sm. Position = 0;
Proxy. SendPic (sm); // the WCF client calls this method to upload the client sm to the server;
}
2. WinFormReceiver background.
Add reference:
Using ITransferPic;
Using System. IO;
Using System. ServiceModel;
View Code
Private void FormReceiver_Load (object sender, EventArgs e)
{
Thread myThread = new Thread (ShowPic); // create a Thread
MyThread. IsBackground = true; // set the background thread (to prevent running after the main program is closed)
MyThread. Start (); // Start the thread
}
Public void ShowPic ()
{
# Create a WCF client like a client
EndpointAddress epAddr = new EndpointAddress ("net. tcp: // localhost: 9600/transferPic ");
NetTcpBinding bind = new NetTcpBinding ();
Bind. MaxBufferPoolSize = 2147483647;
Bind. TransferMode = TransferMode. Streamed;
Bind. maxcompute edmessagesize = 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 (); // copy a filter layer stream;
Ms. Position = 0;
StreamFromServer. CopyTo (ms); // copy the file stream to ms;
If (ms. Length = 0)
{
System. Threading. Thread. Sleep (300); // One execution in 300 milliseconds;
Continue;
}
Bitmap tn = new Bitmap (ms); // creates a Bitmap; converts ms to an image;
PictureBox1.Image = tn;
System. Threading. Thread. Sleep (300); // One execution in 300 milliseconds; Sleep indicates the specified time when the current Thread is suspended;
}
}
4. Run the program.
1. Open the bindirectory in the TransferPicHost file and start “transferpichost.exe ". A form of the console application is displayed, and the message" the image function has been started successfully! "is displayed !".
2. Start the sender and receiver project programs respectively;
(Set "WinFormClient" or "WinFormReceiver" as a startup project, and start “winformreceiver.exe?##winformclient.exe "under the bindirectory of another project folder ")
Click "Browse" on the sender side to select an image, and then click "Upload ". At this time, you will find that the image uploaded by the client is displayed on the form of the receiving end. The program runs successfully.
From Shang0109