using System;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Erp.Common
{
/// <summary>
/// SocketAccept 的摘要说明。
/// </summary>
public class SocketClass
{
int port = 8000 ;
//定义侦听端口号
private Thread thThreadRead ;
//创建线程,用以侦听端口号,接收信息
private TcpListener tlTcpListen ;
//侦听端口号
private bool blistener = true ;
//设定标示位,判断侦听状态
private Socket stRead ;
private string IPAddress;
private int Port;
public SocketClass(string myIPAddress, int myPort)
{
IPAddress = myIPAddress;
Port = myPort;
}
public void ReceiveFile()
{
// System.Net.Sockets.Socket receiveSocket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork
// ,System.Net.Sockets.SocketType.Stream,System.Net.Sockets.ProtocolType.Tcp);
// System.Net.IPEndPoint hostIpEndPoint = new IPEndPoint(System.Net.IPAddress.Parse("192.168.160.112"),8888);
// receiveSocket.Bind(hostIpEndPoint);
// receiveSocket.Listen(2);
// System.IO.FileStream recFs = new FileStream(@"d:\TestErp.txt",System.IO.FileMode.OpenOrCreate);
// Byte[] recByte = new byte[229888];
// System.Net.Sockets.Socket hostSocket = receiveSocket.Accept();
// System.IO.BinaryWriter newFileStr = new BinaryWriter(recFs);
// hostSocket.Receive(recByte);
// newFileStr.Write(recByte,0,recByte.Length - 1);
// recFs.Close();
// hostSocket.Shutdown(System.Net.Sockets.SocketShutdown.Receive);
// hostSocket.Close();
thThreadRead = new Thread ( new ThreadStart ( Listen ) ) ;
//以Listen过程来初始化Thread实例
thThreadRead.Start ( ) ;
//启动线程
// button1.Enabled = false ;
}
public static void SendFile(ArrayList commandArray,string endIPAddress, int recPort)
{
Socket mySocket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork,System.Net.Sockets.SocketType.Stream,System.Net.Sockets.ProtocolType.Tcp);
System.Net.IPEndPoint myEndPoint = new System.Net.IPEndPoint( System.Net.IPAddress.Parse(endIPAddress),recPort);
mySocket.Connect(myEndPoint);
System.Collections.IEnumerator commandList = commandArray.GetEnumerator();
while(commandList.MoveNext())
{
string path = commandList.Current.ToString();
System.IO.FileStream fs = new FileStream(path,System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Read);
if(fs.Length < 1)
{
fs.Close();
continue;
}
Byte[] fsSize = new byte[fs.Length - 1];
System.IO.BinaryReader strRead = new BinaryReader(fs,System.Text.Encoding.Default);
strRead.Read(fsSize,0,fsSize.Length - 1);
string data = System.Text.Encoding.Default.GetString(fsSize);
string fileName = path;
fileName = fileName.Replace(@"C:\","");
data = "FileBegin" + fileName + "FileTextBegin" + data + "FileEnd";
fsSize = null;
fsSize = System.Text.Encoding.Default.GetBytes(data);
mySocket.Send(fsSize);
while (true)
{
Byte[] bytes = new byte[1024];
int bytesRec = mySocket.Receive(bytes);
string data1 = Encoding.ASCII.GetString(bytes,0,bytesRec);
if (data1.IndexOf("OK") > -1)
{
break;
}
}
fs.Close();
}
Byte[] fsSize1 = System.Text.Encoding.Default.GetBytes("停止");
mySocket.Send(fsSize1);
mySocket.Shutdown(System.Net.Sockets.SocketShutdown.Both);
mySocket.Close();
}
public void Listen()
{
try
{
tlTcpListen = new TcpListener ( System.Net.IPAddress.Parse(IPAddress),Port ) ;
//以8888端口号来初始化TcpListener实例
tlTcpListen.Start ( ) ;
//开始监听网络的连接请求
stRead = (Socket)tlTcpListen.AcceptSocket ( ) ;
// stRead.Listen(2);
//通过连接请求,并获得接收数据时使用的Socket实例
EndPoint tempRemoteEP = stRead.RemoteEndPoint ;
IPEndPoint tempRemoteIP = ( IPEndPoint ) tempRemoteEP ;
//获取请求的远程计算机名称
IPHostEntry host = Dns.GetHostByAddress
( tempRemoteIP.Address ) ;
// string sHostName = host.HostName ;
// statusBar1.Text = "已经连接!" ;
//循环侦听
string data;
StringBuilder strBuild = new StringBuilder();
while (blistener)
{
string sTime = DateTime.Now.ToShortTimeString ( ) ;
//获取接收数据时的时间
Byte [] byRead =new Byte [ 80000 ] ;
int iRead = stRead.ReceiveFrom ( byRead , ref tempRemoteEP ) ;
//获得接收的字节数目
Byte [ ] byText = new Byte [ iRead ] ;
//并根据接收到的字节数目来定义字节数组
Array.Copy ( byRead , 0 , byText , 0 , iRead ) ;
string sTemp = System.Text.Encoding.Default.GetString ( byText ) ;
Console.WriteLine(sTemp);
//判断是否为断开连接控制码
if ( sTemp.Trim ( ) .IndexOf( "停止") != -1 )
{
this.InsertDataToTable();
stRead.Close ( ) ;
tlTcpListen.Stop ( ) ;
this.Listen();
//关闭侦听
// // statusBar1.Text = "连接已经关闭!" ;
// thThreadRead.Abort ( ) ;
// //中止线程
return ;
}
else
{
strBuild.Append(sTemp);
}
data = strBuild.ToString();
while(data.IndexOf("FileEnd") != -1)
{
int begin = data.IndexOf("FileBegin");
int end = data.IndexOf("FileEnd");
string dataText = data.Substring(begin,end - begin + 7);
strBuild.Remove(begin,end - begin + 7);
data = data.Remove(begin,end - begin + 7);
string fileName = WriteFile(dataText);
this.SynChroData(fileName);
Byte[] msg = System.Text.Encoding.Default.GetBytes("OK");
stRead.Send(msg);
}
// else
// listBox1.Items.Add ( sTime + " " + sTemp ) ;
}
}
catch ( Exception ex )
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
// MessageBox.Show ( "侦听失败!" , "错误" ) ;
}
}
private void InsertDataToTable()
{
string connStr;
int ret = BusinessServer.DataServer.ConfigManager.GetConnString(out connStr);
if(ret >= 0 )
{
System.Data.SqlClient.SqlConnection conn = new SqlConnection(connStr);
conn.Open();
System.Data.SqlClient.SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Clear();
comm.CommandText = "InsertDataToTable";
comm.ExecuteNonQuery();
}
}
private void SynChroData(string fileName)
{
if(File.Exists(@"C:\" +fileName))
{
string commandString =String.Format("bcp \"{0}\" in {1} -c -U \"sa\" -P \"sa\" ","WebErpBak.dbo." + fileName, @"C:\" + fileName);
ArrayList commandArray = new ArrayList();
commandArray.Add(commandString);
string result = Erp.Common.CommonConsole.CmdLine(commandArray);
}
}
private string WriteFile(string dataText)
{
int nameBegin = dataText.IndexOf("FileBegin");
int nameEnd = dataText.IndexOf("FileTextBegin");
string fileName = dataText.Substring(nameBegin + 9,nameEnd - nameBegin - 9);
dataText = dataText.Remove(0,nameEnd + 13);
string fileData = dataText.Substring(0,dataText.IndexOf("FileEnd"));
using (StreamWriter sw = new StreamWriter(@"C:\" + fileName,false,System.Text.Encoding.Default))
{
// Add some text to the file.
sw.Write(fileData);
}
return fileName;
}
}
}