項目需求,實現cs 客戶端自動更新,由於文件很大,只能通過socket 傳輸更新文件,這樣服務器端需要把更新的文件發送到客戶端。
基於此,做了一個Demo,案例簡單,關鍵部分都有注釋,文章最后附加源文件下載。希望對於正在學習socket 文件傳輸的同學有所幫助
服務端文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
namespace FileServer
{
public partial class Form2 : Form
{
Socket Listensocket;
Thread listenThread;
public Form2()
{
InitializeComponent();
}
// 選擇文件
private void BtnSelectFile_Click( object sender, EventArgs e)
{
if ( this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileInfo fileinfo = new FileInfo( this.openFileDialog1.FileName);
tbFileName.Text = fileinfo.FullName;
tbFileSize.Text = fileinfo.Length.ToString();
}
}
// 開始監聽
private void btnListen_Click( object sender, EventArgs e)
{
if (! string.IsNullOrEmpty(tbFileName.Text) && ! string.IsNullOrEmpty(tbFileSize.Text))
{
// 服務端節點
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse( " 192.168.1.100 "), 8080);
// 創建套接字
Listensocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 綁定IP地址和端口到套接字
Listensocket.Bind(ipep);
// 啟動監聽
Listensocket.Listen( 10);
listBox1.Items.Add( " 開始監聽客戶端的連接請求 ");
// 在一個單獨的線程中監聽客戶連接
listenThread = new Thread(listenClientConnnect);
listenThread.Start();
btnListen.Enabled = false;
}
else
{
MessageBox.Show( " 請瀏覽文件 ", " 提醒信息 ");
}
}
// 監聽函數
private void listenClientConnnect()
{
stopListen(); // 停用
while ( true)
{
// 建立一個與客戶端通信的套接字
Socket CommunicationSocket = Listensocket.Accept();
// 顯示在listbox里面
IPEndPoint clientIP = (IPEndPoint)CommunicationSocket.RemoteEndPoint;
AddMsg( string.Format( " {0} 連接到本服務器 {1} ", clientIP.Address, DateTime.Now.ToString( " yyyy-MM-dd HH:mm:ss ")));
// 創建一個文件對象
FileInfo fileinfo = new FileInfo(tbFileName.Text);
// 打開文件流
FileStream filestream = fileinfo.OpenRead();
// 文件分塊傳輸,分塊的大小,單位為字節
int PacketSize = 5000;
// 分塊的數量
int PacketCount = ( int)(fileinfo.Length / (( long)PacketSize));
// 最后一個分塊的大小
int LastPacketSize = ( int)(fileinfo.Length - (( long)(PacketSize * PacketCount)));
// 發送文件名到接收端,文件名長度最多只允許100個字節
byte[] Fullfilename = new byte[ 100];
if (System.Text.Encoding.UTF8.GetBytes(fileinfo.Name).Length > 100)
{
MessageBox.Show( " 文件名太長 ");
break;
}
else
{
byte[] filename = System.Text.Encoding.UTF8.GetBytes(fileinfo.Name);
for ( int i = 0; i < filename.Length; i++)
Fullfilename[i] = filename[i];
CommunicationSocket.Send(Fullfilename);
}
// 文件按數據包的形式發送,定義數據包的大小
byte[] data = new byte[PacketSize];
// 開始循環發送數據包
for ( int i = 0; i < PacketCount; i++)
{
// 從文件流讀取數據並填充數據包
filestream.Read(data, 0, data.Length);
// 發送數據包
CommunicationSocket.Send(data, 0, data.Length, SocketFlags.None);
}
// 發送最后一個數據包
if (LastPacketSize != 0)
{
data = new byte[LastPacketSize];
filestream.Read(data, 0, data.Length);
// 發送數據包
CommunicationSocket.Send(data, 0, data.Length, SocketFlags.None);
}
filestream.Close();
CommunicationSocket.Close();
AddMsg( string.Format( " 向{0} 發送 文件 已完成 {1} ", clientIP, DateTime.Now.ToString( " yyyy-MM-dd HH:mm:ss ")));
}
}
// 關閉
private void Form2_FormClosed( object sender, FormClosedEventArgs e)
{
if (Listensocket!= null)
{
Listensocket.Close();
}
}
// 停止監聽
private void btnStop_Click( object sender, EventArgs e)
{
if (listenThread.IsAlive)
{
listenThread.Abort();
btnListen.Enabled = true;
btnStop.Enabled = false;
if (Listensocket!= null)
{
Listensocket.Close();
}
listBox1.Items.Add( " 服務器監聽已經停止... ");
}
}
// 加載
private void Form2_Load( object sender, EventArgs e)
{
btnStop.Enabled = false;
btnListen.Enabled = true;
}
// 停止監聽
private void stopListen()
{
if (btnStop.InvokeRequired)
{
Action stopAction = () => { stopListen(); };
btnStop.Invoke(stopAction);
}
else
{
btnStop.Enabled = true;
}
}
// 向listBox中增加信息
private void AddMsg( string msgStr)
{
if (listBox1.InvokeRequired)
{
Action< string> myAction = (p) => { AddMsg(p); };
this.listBox1.Invoke(myAction, msgStr);
}
else
{
this.listBox1.Items.Add(msgStr);
}
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
namespace FileServer
{
public partial class Form2 : Form
{
Socket Listensocket;
Thread listenThread;
public Form2()
{
InitializeComponent();
}
// 選擇文件
private void BtnSelectFile_Click( object sender, EventArgs e)
{
if ( this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileInfo fileinfo = new FileInfo( this.openFileDialog1.FileName);
tbFileName.Text = fileinfo.FullName;
tbFileSize.Text = fileinfo.Length.ToString();
}
}
// 開始監聽
private void btnListen_Click( object sender, EventArgs e)
{
if (! string.IsNullOrEmpty(tbFileName.Text) && ! string.IsNullOrEmpty(tbFileSize.Text))
{
// 服務端節點
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse( " 192.168.1.100 "), 8080);
// 創建套接字
Listensocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 綁定IP地址和端口到套接字
Listensocket.Bind(ipep);
// 啟動監聽
Listensocket.Listen( 10);
listBox1.Items.Add( " 開始監聽客戶端的連接請求 ");
// 在一個單獨的線程中監聽客戶連接
listenThread = new Thread(listenClientConnnect);
listenThread.Start();
btnListen.Enabled = false;
}
else
{
MessageBox.Show( " 請瀏覽文件 ", " 提醒信息 ");
}
}
// 監聽函數
private void listenClientConnnect()
{
stopListen(); // 停用
while ( true)
{
// 建立一個與客戶端通信的套接字
Socket CommunicationSocket = Listensocket.Accept();
// 顯示在listbox里面
IPEndPoint clientIP = (IPEndPoint)CommunicationSocket.RemoteEndPoint;
AddMsg( string.Format( " {0} 連接到本服務器 {1} ", clientIP.Address, DateTime.Now.ToString( " yyyy-MM-dd HH:mm:ss ")));
// 創建一個文件對象
FileInfo fileinfo = new FileInfo(tbFileName.Text);
// 打開文件流
FileStream filestream = fileinfo.OpenRead();
// 文件分塊傳輸,分塊的大小,單位為字節
int PacketSize = 5000;
// 分塊的數量
int PacketCount = ( int)(fileinfo.Length / (( long)PacketSize));
// 最后一個分塊的大小
int LastPacketSize = ( int)(fileinfo.Length - (( long)(PacketSize * PacketCount)));
// 發送文件名到接收端,文件名長度最多只允許100個字節
byte[] Fullfilename = new byte[ 100];
if (System.Text.Encoding.UTF8.GetBytes(fileinfo.Name).Length > 100)
{
MessageBox.Show( " 文件名太長 ");
break;
}
else
{
byte[] filename = System.Text.Encoding.UTF8.GetBytes(fileinfo.Name);
for ( int i = 0; i < filename.Length; i++)
Fullfilename[i] = filename[i];
CommunicationSocket.Send(Fullfilename);
}
// 文件按數據包的形式發送,定義數據包的大小
byte[] data = new byte[PacketSize];
// 開始循環發送數據包
for ( int i = 0; i < PacketCount; i++)
{
// 從文件流讀取數據並填充數據包
filestream.Read(data, 0, data.Length);
// 發送數據包
CommunicationSocket.Send(data, 0, data.Length, SocketFlags.None);
}
// 發送最后一個數據包
if (LastPacketSize != 0)
{
data = new byte[LastPacketSize];
filestream.Read(data, 0, data.Length);
// 發送數據包
CommunicationSocket.Send(data, 0, data.Length, SocketFlags.None);
}
filestream.Close();
CommunicationSocket.Close();
AddMsg( string.Format( " 向{0} 發送 文件 已完成 {1} ", clientIP, DateTime.Now.ToString( " yyyy-MM-dd HH:mm:ss ")));
}
}
// 關閉
private void Form2_FormClosed( object sender, FormClosedEventArgs e)
{
if (Listensocket!= null)
{
Listensocket.Close();
}
}
// 停止監聽
private void btnStop_Click( object sender, EventArgs e)
{
if (listenThread.IsAlive)
{
listenThread.Abort();
btnListen.Enabled = true;
btnStop.Enabled = false;
if (Listensocket!= null)
{
Listensocket.Close();
}
listBox1.Items.Add( " 服務器監聽已經停止... ");
}
}
// 加載
private void Form2_Load( object sender, EventArgs e)
{
btnStop.Enabled = false;
btnListen.Enabled = true;
}
// 停止監聽
private void stopListen()
{
if (btnStop.InvokeRequired)
{
Action stopAction = () => { stopListen(); };
btnStop.Invoke(stopAction);
}
else
{
btnStop.Enabled = true;
}
}
// 向listBox中增加信息
private void AddMsg( string msgStr)
{
if (listBox1.InvokeRequired)
{
Action< string> myAction = (p) => { AddMsg(p); };
this.listBox1.Invoke(myAction, msgStr);
}
else
{
this.listBox1.Items.Add(msgStr);
}
}
}
}
客戶端文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace FileClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// 連接
private void btnConnect_Click( object sender, EventArgs e)
{
Thread mythread = new Thread(GetData);
mythread.Start();
}
// 接受數據
private void GetData()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse( " 192.168.1.100 "), 8080);
Socket clientsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listBox1.Items.Add( " 連接遠程服務器成功 ");
clientsocket.Connect(ipep);
}
catch (Exception)
{
listBox1.Items.Add( " 連接遠程服務器失敗 ");
}
// 接收文件的名稱
string filename = System.Text.Encoding.UTF8.GetString(ReceiveStrToByte(clientsocket)).Split( ' \0 ')[ 0];
// 創建一個新文件
FileStream MyFileStream = new FileStream(filename, FileMode.Create, FileAccess.Write);
int PacketSize = 5000;
// 定義一個完整數據包緩存
byte[] data = new byte[PacketSize];
while ( true)
{
int revcount = clientsocket.Receive(data, 0, PacketSize, SocketFlags.None);
if (revcount == 0)
{
data = null;
break;
}
// 處理最后一個數據包
if (revcount != PacketSize)
{
byte[] lastdata = new byte[revcount];
for ( int i = 0; i < revcount; i++)
lastdata[i] = data[i];
// 將接收到的最后一個數據包寫入到文件流對象
MyFileStream.Write(lastdata, 0, lastdata.Length);
lastdata = null;
}
else
{
// 將接收到的數據包寫入到文件流對象
MyFileStream.Write(data, 0, data.Length);
}
}
// 關閉文件流
MyFileStream.Close();
// 關閉套接字
clientsocket.Close();
listBox1.Items.Add( string.Format( " {0}接收完畢 ", filename));
}
private byte[] ReceiveStrToByte(Socket s)
{
try
{
byte[] dataninfo = new byte[ 100];
int revByteNum = s.Receive(dataninfo, 0, dataninfo.Length, SocketFlags.None);
byte[] retByte = new byte[revByteNum];
for ( int i = 0; i < revByteNum; i++)
retByte[i] = dataninfo[i];
return retByte;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace FileClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// 連接
private void btnConnect_Click( object sender, EventArgs e)
{
Thread mythread = new Thread(GetData);
mythread.Start();
}
// 接受數據
private void GetData()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse( " 192.168.1.100 "), 8080);
Socket clientsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listBox1.Items.Add( " 連接遠程服務器成功 ");
clientsocket.Connect(ipep);
}
catch (Exception)
{
listBox1.Items.Add( " 連接遠程服務器失敗 ");
}
// 接收文件的名稱
string filename = System.Text.Encoding.UTF8.GetString(ReceiveStrToByte(clientsocket)).Split( ' \0 ')[ 0];
// 創建一個新文件
FileStream MyFileStream = new FileStream(filename, FileMode.Create, FileAccess.Write);
int PacketSize = 5000;
// 定義一個完整數據包緩存
byte[] data = new byte[PacketSize];
while ( true)
{
int revcount = clientsocket.Receive(data, 0, PacketSize, SocketFlags.None);
if (revcount == 0)
{
data = null;
break;
}
// 處理最后一個數據包
if (revcount != PacketSize)
{
byte[] lastdata = new byte[revcount];
for ( int i = 0; i < revcount; i++)
lastdata[i] = data[i];
// 將接收到的最后一個數據包寫入到文件流對象
MyFileStream.Write(lastdata, 0, lastdata.Length);
lastdata = null;
}
else
{
// 將接收到的數據包寫入到文件流對象
MyFileStream.Write(data, 0, data.Length);
}
}
// 關閉文件流
MyFileStream.Close();
// 關閉套接字
clientsocket.Close();
listBox1.Items.Add( string.Format( " {0}接收完畢 ", filename));
}
private byte[] ReceiveStrToByte(Socket s)
{
try
{
byte[] dataninfo = new byte[ 100];
int revByteNum = s.Receive(dataninfo, 0, dataninfo.Length, SocketFlags.None);
byte[] retByte = new byte[revByteNum];
for ( int i = 0; i < revByteNum; i++)
retByte[i] = dataninfo[i];
return retByte;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
}
}
程序源文件下載:源程序下載