功能介紹
主要是使用WCF框架實現從客戶端上傳圖片到服務端並在服務端顯示的基本功能
一
然後添加浏覽按鈕下的後台代碼
View Code
string fileName =
//浏覽選擇上傳內容
private void btnBrowser_Click(object sender
{
//string fileName =
OpenFileDialog openFileDialog = new OpenFileDialog()
if (openFileDialog
{
fileName = openFileDialog
txtPicName
pictureBox
}
else
return;//未選中文件則返回
}
將WinFomClient設為啟動項目
當你選擇圖片後
二
該實例采用的是
(
(
View Code
[ServiceContract]
public interface ITransferPicService
{
[OperationContract]//操作契約
Stream GetPic()
[OperationContract]
void SendPic(Stream transferPic)
}
(
(
View Code
public class TransferPicService : ITransferPicService
{
public static Stream PicSource = new MemoryStream()
/// <summary>
/// 從服務端下載圖片到本地 (上傳和下載都是拷貝的過程)
/// </summary>
/// <returns></returns>
public Stream GetPic()
{
MemoryStream ms = new MemoryStream()
PicSource
PicSource
ms
return ms;//然後在返回客戶端
}
/// <summary>
/// 從客戶端上傳圖片到服務端(將客戶端的Stream拷貝給服務端的Stream)
/// </summary>
/// <param name=
public void SendPic(Stream transferPic)
{
PicSource
transferPic
}
}
自身托管宿主
添加引用
using System
using ITransferPic;
using System
View Code
class Program
{
static void Main(string[] args)
{
NetTcpBinding bind = new NetTcpBinding()
bind
bind
bind
bind
//超出using 范圍程序會自動釋放
using (ServiceHost host = new ServiceHost(typeof(TransferPic
{
host
if (host
{
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior()
behavior
behavior
host
}
host
host
Console
}
}
}
三
添加引用
using System
using System
using ITransferPic;
View Code
//執行上傳功能
private void btnUpload_Click(object sender
{
//pictureBox
//讀取流
FileStream fs = new FileStream(fileName
Stream sm = new MemoryStream()
fs
fs
//拷貝完成之後進行上傳
EndpointAddress epAddr = new EndpointAddress(
NetTcpBinding bind = new NetTcpBinding()
bind
bind
bind
bind
//創建一個工廠
ITransferPicService proxy = ChannelFactory<ITransferPicService>
sm
proxy
}
添加引用
using ITransferPic;
using System
using System
View Code
private void FormReceiver_Load(object sender
{
Thread myThread = new Thread(ShowPic)
myThread
myThread
}
public void ShowPic()
{
#region 同客戶端一樣
EndpointAddress epAddr = new EndpointAddress(
NetTcpBinding bind = new NetTcpBinding()
bind
bind
bind
bind
//創建一個通道
ITransferPicService proxy = ChannelFactory<ITransferPicService>
#endregion
while (true)
{
Stream streamFromServer = proxy
MemoryStream ms = new MemoryStream()
ms
streamFromServer
if (ms
{
System
continue;
}
Bitmap tn = new Bitmap(ms)
pictureBox
System
}
}
四
(將
點擊發送端
From:http://tw.wingwit.com/Article/program/net/201311/12342.html