You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

291 lines
9.7 KiB
C#

using HuizhongLibrary.Log;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace HuizhongLibrary.Network
{
public class SendSocket
{
public string IpAddress = "127.0.0.1";
public int Port = 20000;
public static int OutTime = 10; //默认超时
Socket socket = null;
AutoResetEvent AutoReset = new AutoResetEvent(false);
string error = "";
System.Threading.Timer time1 = null;
public byte[] Data = null;
public byte[] RevData = null;
bool IsRun = false;
#region 发送
public void Send(byte[] buffer)
{
IsRun = true;
Data = buffer;
RevData = null;
time1 = new System.Threading.Timer(new System.Threading.TimerCallback(Timer_SocketConnect), null, 2000, 0);
Action hand = new Action(this.Connect);
hand.BeginInvoke(null, null);
AutoReset.WaitOne(SendSocket.OutTime * 1000, false);
}
#endregion
#region 发送
public void BeginSend(byte[] buffer)
{
IsRun = true;
Data = buffer;
RevData = null;
time1 = new System.Threading.Timer(new System.Threading.TimerCallback(Timer_SocketConnect), null, 2000, 0);
Action hand = new Action(this.BeginConnect);
hand.BeginInvoke(null, null);
}
#endregion
#region 连接
void Connect()
{
try
{
IPAddress broadcast = IPAddress.Parse(this.IpAddress);
IPEndPoint ep = new IPEndPoint(broadcast,this.Port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.LingerState = new LingerOption(true, 0);
socket.SendTimeout = 5000;
socket.ReceiveBufferSize = 4096 * 1024;
//ErrorFollow.TraceWrite("连接金唐服务", "", "Ip:"+ IpAddress+";Port:"+Port);
socket.Connect(ep);
//ErrorFollow.TraceWrite("连接金唐服务", "成功", "Ip:" + IpAddress + ";Port:" + Port);
time1.Dispose();
int i=socket.Send(Data, 0, Data.Length, SocketFlags.None);
if (i == 0) { error = "发送数据失败"; }
while (IsRun)
{
if (socket.Available > 0)
{
RevData = new byte[socket.Available];
socket.Receive(RevData);
break;
}
else
{
//ErrorFollow.TraceWrite("金唐服务", "", "未接收到数据,等待100毫秒后重新接收");
Thread.Sleep(100);
}
}
Stop();
}
catch (Exception ex)
{
error = ex.Message;
}
}
#endregion
#region 连接
void BeginConnect()
{
try
{
IPAddress broadcast = IPAddress.Parse(this.IpAddress);
IPEndPoint ep = new IPEndPoint(broadcast, this.Port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.LingerState = new LingerOption(true, 0);
socket.SendTimeout = 5000;
socket.Connect(ep);
time1.Dispose();
socket.Send(Data, 0, Data.Length, SocketFlags.None);
int index = 1;
int CountNum = SendSocket.OutTime * 1000 / 100;
while (IsRun)
{
if (socket.Available > 0)
{
RevData = new byte[socket.Available];
socket.Receive(RevData);
break;
}
else
{
Thread.Sleep(100);
index++;
if (index > CountNum) break;
}
}
Stop();
}
catch (Exception ex)
{
error = ex.Message;
}
}
#endregion
#region 关闭
public void Stop()
{
AutoReset.Set();
IsRun = false;
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch
{ }
try
{
socket.Close();
}
catch
{ }
}
#endregion
#region 检测连接是否成功
void Timer_SocketConnect(object state)
{
try
{
time1.Dispose();
if (socket.Connected == false)
{
error = "连接服务器失败";
Stop();
}
}
catch
{}
}
#endregion
#region 发送数据
public static int KTSendRcv(string ip, int port, string sendbuf, out string recvbuf)
{
byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(sendbuf);
SendSocket model = new SendSocket();
model.IpAddress = ip;
model.Port = port;
model.Send(buffer);
recvbuf = "";
if (string.IsNullOrEmpty(model.error) == false) { recvbuf = model.error; return 1; }
if (model.RevData == null)
{
recvbuf = model.error;
model.Stop();
return 2;
}
recvbuf = System.Text.Encoding.GetEncoding("GB2312").GetString(model.RevData, 0, model.RevData.Length);
return 0;
}
#endregion
#region 异步发送数据
public static void BeginKTSendRcv(string ip, int port, string sendbuf)
{
byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(sendbuf);
SendSocket model = new SendSocket();
model.IpAddress = ip;
model.Port = port;
model.BeginSend(buffer);
}
#endregion
#region 发送数据
public static int KTSendRcv(string ip,int port,byte[] sendbuf, out byte[] recvbuf)
{
SendSocket model = new SendSocket();
model.IpAddress = ip;
model.Port = port;
model.Send(sendbuf);
recvbuf = null;
if (string.IsNullOrEmpty(model.error) == false) return 1;
if (model.RevData == null)
{
model.Stop();
return 2;
}
recvbuf = model.RevData;
return 0;
}
#endregion
#region 异步发送数据
public static void BeginKTSendRcv(string ip, int port, byte[] sendbuf)
{
SendSocket model = new SendSocket();
model.IpAddress = ip;
model.Port = port;
model.BeginSend(sendbuf);
}
#endregion
#region 文件发送
public static void SendFile(string IpAddress,int Port,string FilePath,Action<string,int> ActionProgress)
{
Action<string, int, string, Action<string,int>> act = new Action<string, int, string, Action<string,int>>(BeginSendFile);
act.BeginInvoke(IpAddress, Port, FilePath, ActionProgress, null, null);
}
public static void BeginSendFile(string IpAddress, int Port, string FilePath, Action<string,int> ActionProgress)
{
try
{
IPAddress broadcast = IPAddress.Parse(IpAddress);
IPEndPoint ep = new IPEndPoint(broadcast, Port);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.LingerState = new LingerOption(true, 0);
socket.SendTimeout = 5000;
socket.ReceiveBufferSize = 50 * 1024;
socket.Connect(ep);
NetworkStream ns = new NetworkStream(socket);
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
fs.Position = 0;
byte[] fileBuffer = new byte[1024 * 32]; // 每次传4KB
int bytesRead;
int totalBytes = 0;
int index = 0;
do
{
bytesRead = fs.Read(fileBuffer, 0, fileBuffer.Length);
if (bytesRead == 0) break;
ns.Write(fileBuffer, 0, bytesRead);
totalBytes += bytesRead; // 发送了的字节数
double Percent = Convert.ToDouble(totalBytes) / Convert.ToDouble(fs.Length) * 100;
ActionProgress.Invoke(IpAddress,Convert.ToInt32(Percent));
//Thread.Sleep(10);
index++;
//if (index == 10)
//{
// Thread.Sleep(10);
// index = 0;
//}
} while (bytesRead > 0);
ns.Close(5000);
socket.Close(5000);
fs.Close();
fs = null;
ns = null;
socket = null;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
ActionProgress.Invoke(IpAddress,-1);
}
}
#endregion
}
}