發送端部分代碼:
public void startSendFileThread() {
try
{
Thread sendFileThread = new Thread(new ThreadStart(sendFile));
sendFileThread.Start();
}
catch {
MessageBox.Show("線程開啟或線程發送過中遇到問題失敗。。。。。。");
this.sendFlag = false;
}
finally
{
}
}
public void sendFile()
{
public Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(userIP),userPort);
try
{
//因為客戶端只是用來向特定的服務器發送信息,所以不需要綁定本機的IP和端口。不需要監聽。
socketClient.SendBufferSize = 1024 * 1024*10;
socketClient.ReceiveBufferSize = 1024 * 1024*10;
socketClient.Connect(ipep);
// MessageBox.Show("connected!!");
}
catch (SocketException e)
{
Console.WriteLine("unable to connect to server");
Console.WriteLine(e.ToString());
}
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
int partSize = 1024 * 100;
long fileLength = fs.Length;
long offset = 0;
while (true)
{
if (offset + partSize >=fileLength)
partSize = Convert.ToInt32(fileLength - offset);
byte[] temp = new byte[partSize];
fs.Position = offset;
fs.Read(temp, 0, partSize);
socketClient.Send(temp, temp.Length, SocketFlags.None);//將數據發送到指定的終結點
// myControl.TraFransfersSize += partSize;
if (offset + partSize >= fileLength)
break;
offset += partSize;
}
//myChat.Rich_Out.AppendText("發送完成: " + fileName + "\n");
socketClient.Shutdown( SocketShutdown.Both);
socketClient.Close();
// myChat.RemoveFileInfoFromControl(fileName);
}
接收端部分代碼:
public void Listener() //監聽 本地端口5421
{
if (classTCPSocket == null)
classTCPSocket = new ClassTCPSocket(5421);
else
{
try
{
thdUdp = new Thread(new ThreadStart(GetUDPData)); //創建一個線程
thdUdp.Start(); //執行當前線程
}
catch (Exception e)
{
MessageBox.Show(e.ToString()); //顯示線程的錯誤信息
}
}
}
public void GetUDPData() //獲取當前接收的消息
{
serverSocket = classTCPSocket.getTCPSocker().Accept();//等到一個TCPSocker
byte[] Data =null;
int number = 0;
bool flag = true;
while (flag)
{
Data = new byte[1024 * 10];
if ((number = serverSocket.Receive(Data)) != 0)
{
FileStream fs = null;
try
{
fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite,FileShare.ReadWrite);// File.OpenWrite(filePath);
fs.Seek(0, SeekOrigin.End);//將該流的當前位值設為0
fs.Write(Data, 0, number);//向文件中寫入當前接收的信息
// myControl.TraFransfersSize += number;
}
finally
{
fs.Close();
}
}
else flag=false;
}
// myChat.Rich_Out.AppendText("接收成功: " + fileName + "\n文件大小:"+GetText(myControl.TraFransfersSize)+"\n");
DoCleanOperation();
}
public void DoCleanOperation(){
if (serverSocket.Connected)
{
serverSocket.Shutdown(SocketShutdown.Both);
serverSocket.Close();
}
classTCPSocket.Active = false;
// myChat.RemoveFileInfoFromControl(fileName);// panelSendFile.Controls.Remove(myControl);
thdUdp.Abort();
}
www.2cto.com
//ClassTCPSocket 類
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;
using System.Threading;
namespace QQClient
{
public class ClassTCPSocket
{
Socket tcpSocket = null;
private int localPort = 5421;
public int LocalPort
{
get { return localPort; }
set { localPort = value; }
}
public ClassTCPSocket(int localPort) {
this.localPort = localPort;
init();
}
private string localHost = "127.0.0.1";
public string LocalHost
{
get { return localHost; }
set { localHost = value; }
}
private bool active = false;
public bool Active
{
get { return active; }
set //該屬性讀取值
{
active = value;
if (tcpSocket == null)
init();
if (active)
{
openListen();
}
else
stopListen();
}
}
public void init(){
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ClassGetLocalInfo.getLocalhostIP()), localPort);//定義一網絡端點,將本地IP地址和端口號以網絡端點存儲
tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//定義一個Socket
tcpSocket.Bind(ipep);//Socket與本地的一個終結點相關聯
}
public void openListen() {
if (this.tcpSocket != null)
{
tcpSocket.Listen(10);
//MessageBox.Show(tcpSocket.AddressFamily+":"+tcpSocket.LocalEndPoint);
}
else
{
init();
tcpSocket.Listen(10);
}
}
public void stopSocket() {
if (this.tcpSocket != null)
{
tcpSocket.Shutdown(SocketShutdown.Both);
tcpSocket.Close();
}
}
public void stopListen() {
if (this.tcpSocket != null && this.tcpSocket.Connected)
{
tcpSocket.Shutdown(SocketShutdown.Both);
}
}
public Socket getTCPSocker(){
return tcpSocket;
}
}
}
摘自 love254443233的專欄