多文件传输c# winform Socket并把传输文件保存到Oracle数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
using System.Net;
using System.Threading;
using System.Net.Sockets;
 
using System.IO;
 
using System.Data.OracleClient;
using System.Data.OleDb;
 
namespace OverSpeedMIS
{
 public partial class FormSystemOnLineObject : Form
 {
  public FormSystemOnLineObject()
  {
   InitializeComponent();
 
   //不显示出dataGridView1的最后一行空白
   dataGridView1.AllowUserToAddRows = false;
  }
 
  /// <summary>   
  /// 作者:黑色头发  
  /// C# WinForm Socket传递多个文件并保存到oracle数据库的Blob字段  
  /// blog:http://heisetoufa.iteye.com  
  /// 静网:http://www.heisetoufa.cn  
  /// </summary>
 
 
  #region 定义变量
 
 
  TcpListener lisner;
  Thread TempThread;
 
  int xhMax = 0;//序号
 
  DBConnection dbc = new DBConnection();
  OleDbConnection con;
  OracleConnection connn;
  OracleDataReader odrRepeat;
 
  #endregion
 
 
  #region 进入窗体即启动服务
 
 
  private void FormSystemOnLineObject_Load(object sender, EventArgs e)
  {
   //判断文件存不存在
   if (!Directory.Exists(@txtFileSaveDir.Text))//若文件夹不存在则新建文件夹
   {
    Directory.CreateDirectory(@txtFileSaveDir.Text); //新建文件夹
   }
    
   //开启接收线程
   TempThread = new Thread(new ThreadStart(this.StartReceive));
   TempThread.IsBackground = true;//设置为后台线程
   TempThread.Start();
  }
   
 
 
  private void StartReceive()
  {
   //创建一个网络端点
   IPEndPoint ipep = new IPEndPoint(IPAddress.Any, int.Parse("2005"));
 
   //创建网络监听
   lisner = new TcpListener(ipep);
 
   lisner.Start();
 
   while (true)
   {
     
    ////确认连接               
    if (!lisner.Pending())
    {
      
     Thread.Sleep(1000);
     continue;
    }
 
    //MessageBox.Show("1");
 
    Socket client = lisner.AcceptSocket();
 
    //获得客户端节点对象
    IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
 
    //获得[文件名]
    string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
 
    //获得[包的大小]
    string bagSize =   System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
 
    //获得[包的总数量]
    int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));
 
    //获得[最后一个包的大小]
    string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
     
    //创建一个新文件
    string fileFullName = txtFileSaveDir.Text + "\\" + SendFileName;
     
    FileStream MyFileStream = new FileStream(fileFullName, FileMode.Create, FileAccess.Write, FileShare.Read);
     
    //已发送包的个数
    int SendedCount = 0;
 
    while (true)
    {
     byte[] data = TransferFiles.ReceiveVarData(client);
     if (data.Length == 0)
     {
      break;
     }
     else
     {
      SendedCount++;
      //将接收到的数据包写入到文件流对象
      MyFileStream.Write(data, 0, data.Length);
     }
    }
     
     
    //关闭文件流
    MyFileStream.Close();
 
     
    //关闭套接字
    client.Close();
    IPHostEntry ipHostEntry = Dns.GetHostEntry(IPAddress.Parse(clientep.Address.ToString()));
    string clientHostName = ipHostEntry.HostName;
 
 
    //················································
    //保存接收的文件到数据库里
    if (checkBox2.Checked == true)
    {
     string cnnstr = "provider=OraOLEDB.Oracle;data source=zlkj_kk;User Id=kk;Password=kk;";
     con = new OleDbConnection(cnnstr);
     try
     {
      con.Open();
     }
     catch
     { }
     OleDbCommand cmd = new OleDbCommand(cnnstr, con);
 
     cmd.CommandType = CommandType.Text;
     cmd.CommandText = cnnstr;
 
     //string imgPath = @"d:\aa\a.jpg";//图片文件所在路径+文件名
 
     string imgPath = @fileFullName;//图片文件所在路径+文件名
 
     FileStream file = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
     Byte[] imgByte = new Byte[file.Length];//把图片转成 Byte型 二进制流
     file.Read(imgByte, 0, imgByte.Length);//把二进制流读入缓冲区
     file.Close();
 
 
     //========================================================================================
     //插入之前检查有有无重复数据
     connn = dbc.getConnection();//获得conn连接
 
     try
     {
      connn.Open();
 
      OracleCommand cmdd = connn.CreateCommand();
 
      cmdd.CommandText = "SELECT max(cast( xh as int)) as xh FROM kk.kkcltj ";//插入之前检查有有无重复数据
      odrRepeat = cmdd.ExecuteReader();//创建一个OracleDateReader对象   
      if (odrRepeat.Read())//读取数据,如果odr.Read()返回为true的话,就说明到登陆成功了
      {
       xhMax = Convert.ToInt32(odrRepeat["xh"].ToString());
      }
     }
     catch (Exception ee)
     {
      MessageBox.Show(ee.Message.ToString());
     }
 
     //========================================================================================
 
 
     string strr = fileFullName.Substring(fileFullName.LastIndexOf("\\") + 1).ToString();//不带路径的文件名
     //MessageBox.Show("                    "+strr);
 
     DateTime dTime;
     string kkdd = "";//卡口地点
     string xsfx = "";//行驶方向
 
     string xscd = "";//行驶车道
     int xzsd = 0;//限制速度
     int sjsd = 0;//实际速度
     string csbz = "";//超速标志
     string hpzl = "";//号牌种类
     string hphmm = "";//号牌号码
 
     if (fileFullName.Length > 42)
     {
      int yearFile = Convert.ToInt32(strr.Substring(0, 4));//截取年
      int monthFile = Convert.ToInt32(strr.Substring(4, 2));//截取月
      int dateFile = Convert.ToInt32(strr.Substring(6, 2));//截取日
      int hourFile = Convert.ToInt32(strr.Substring(8, 2));//截取时
      int minuteFile = Convert.ToInt32(strr.Substring(10, 2));//截取分
      int secondFile = Convert.ToInt32(strr.Substring(12, 2));//截取秒
      //int millisecondFile = Convert.ToInt32(strr.Substring(14, 3));//
 
      dTime = new DateTime(yearFile, monthFile, dateFile, hourFile, minuteFile, secondFile);
      //MessageBox.Show(dt.ToString("yyyy-MM-dd HH-mm-ss fff"));
 
  
 
      kkdd = strr.Substring(14, 4);//卡口地点
      xsfx = strr.Substring(18, 1); ;//行驶方向
 
      xscd = strr.Substring(19, 1);//行驶车道
      xzsd = Convert.ToInt32(strr.Substring(20, 3));//限制速度
      sjsd = Convert.ToInt32(strr.Substring(23, 3));//实际速度
      csbz = strr.Substring(26, 1);//超速标志
      hpzl = strr.Substring(27, 2);//号牌种类
      hphmm = strr.Substring(29, 7);//号牌号码
      //照片大小
 
 
      //—————————————————————————————————————————————
      //把信息插入数据库
 
      xhMax++;
 
      //MessageBox.Show(xhMax.ToString());
      cmd.CommandText = "insert into kk.kkcltj(xh,zpsj,kkdd,xsfx,xscd,xzsd,sjsd,csbz,hphm,hpzl,zpdx,zp) values('" + xhMax.ToString() + "',to_date('" + dTime.ToString() + "','YYYY-MM-DD HH24:MI:SS'),'" + kkdd + "','" + xsfx + "' ,'" + xscd + "', " + xzsd + ", " + sjsd + ", '" + csbz + "','" + hphmm + "','" + hpzl + "','" + imgByte.Length.ToString() + "',:zp ) ";//正常sql语句插入数据库
 
      //MessageBox.Show(cmd.CommandText.ToString());
 
 
      cmd.Parameters.Add("zp", System.Data.OleDb.OleDbType.Binary, imgByte.Length);
      cmd.Parameters[0].Value = imgByte;
 
      try
      {
       cmd.ExecuteNonQuery();
       //MessageBox.Show("插入成功");
      }
      catch (System.Exception e1)
      {
       MessageBox.Show(e1.Message);
      }
 
      //—————————————————————————————————————————————
     }
     else
     {
 
     }
    }
    else if (checkBox1.Checked == true)
    {
     //AddRow(clientHostName, "说明占位", clientep.Address, SendedCount, SendFileName, bagCount, "连接类型占位", "关联对象占位");
    }
    else if (checkBox1.Checked == false && checkBox2.Checked == false)
    {
     MessageBox.Show("选择保存到硬盘还是数据库");
     break;
    }
 
    //················································
    con.Close();
    connn.Close();
    odrRepeat.Close();
 
    //填加到dgv里
    //文件大小,IP,已发送包的个数,文件名,包的总量,最后一个包的大小 
    //AddRow(clientHostName, "说明占位", clientep.Address, SendedCount, SendFileName, bagCount, bagLast);
    AddRow(clientHostName, "说明占位", clientep.Address, SendedCount, SendFileName, bagCount, "连接类型占位", "关联对象占位");
   }
  }
 
 
  private delegate void DelAddRow(object o1, object o2, object o3, object o4, object o5, object o6, object o7, object o8);
 
  private void AddRow(object o1, object o2, object o3, object o4, object o5, object o6, object o7, object o8)
  {
   if (InvokeRequired)
   {
    DelAddRow dar = new DelAddRow(AddRow);
    this.Invoke(dar, o1, o2, o3, o4, o5, o6, o7, o8);
    return;
   }
   this.dataGridView1.Rows.Add(o1, o2, o3, o4, o5, o6, o7, o8);
  }
   
 
 
  #endregion
 
 
  #region   拦截Windows消息,关闭窗体时执行
  protected override void WndProc(ref   Message m)
  {
   const int WM_SYSCOMMAND = 0x0112;
   const int SC_CLOSE = 0xF060;
   if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
   {
    //捕捉关闭窗体消息  
    //   User   clicked   close   button  
    //this.WindowState = FormWindowState.Minimized;//把右上角红叉关闭按钮变最小化
 
    TempThread.Abort();
    lisner.Stop();
 
 
    ServiceStop();
   }
   base.WndProc(ref   m);
  }
  #endregion
 
 
  #region 停止服务
 
  //停止服务
  private void ServiceStop()
  {
   try
   {
     
   }
   catch { }
 
   try
   {
 
   }
   catch { }
  }
 
  #endregion
 
  private void button1_Click(object sender, EventArgs e)
  {
   if (fbdFileSave.ShowDialog() == DialogResult.OK)
   {
    txtFileSaveDir.Text = fbdFileSave.SelectedPath;
   }
  }
 
  private void toolStripStatusLabel1_Click(object sender, EventArgs e)
  {
 
  }
 
  private void toolStripStatusLabel2_Click(object sender, EventArgs e)
  {
   System.Diagnostics.Process.Start("http://heisetoufa.iteye.com"); 
  }
 }
}

 

posted @   Devil_jim  阅读(909)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示