1 using System;
2 using System.Collections.Generic;
3 using System.Net;
4 using System.Net.Sockets;
5 using System.Threading;
6
7 namespace TestDemo
8 {
9 /// <summary>
10 /// 处理TCP数据的类(客户端)
11 /// </summary>
12 public class Tcp
13 {
14 /// <summary>
15 /// TCP客户端对象
16 /// </summary>
17 private TcpClient tcpClient;
18
19 /// <summary>
20 /// 本机IP地址
21 /// </summary>
22 private readonly string localIP;
23
24 /// <summary>
25 /// 本机端口号
26 /// </summary>
27 private readonly int localPort;
28
29 /// <summary>
30 /// 构造函数
31 /// </summary>
32 /// <param name="ip"></param>
33 /// <param name="port"></param>
34 public Tcp(string ip = null, int port = 0)
35 {
36 this.localIP = ip;
37 this.localPort = port;
38 }
39
40 /// <summary>
41 /// 创建TCP连接
42 /// </summary>
43 /// <param name="ip"></param>
44 /// <param name="port"></param>
45 public void Connect(string ip, int port)
46 {
47 // 实例化TCP客户端
48 if (localIP != null)
49 {
50 IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(localIP), localPort);
51 tcpClient = new TcpClient(iPEndPoint);
52 }
53 else
54 {
55 IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, localPort);
56 tcpClient = new TcpClient(iPEndPoint);
57 }
58 // 创建TCP连接
59 tcpClient = new TcpClient();
60 if (!tcpClient.ConnectAsync(ip, port).Wait(1000) || !tcpClient.Connected)
61 {
62 throw new Exception(String.Format("TCP连接失败:{0}:{1}", ip, port));
63 }
64 }
65
66 /// <summary>
67 /// 关闭TCP连接
68 /// </summary>
69 public void Close()
70 {
71 if (tcpClient != null)
72 {
73 tcpClient.Close();
74 }
75 }
76
77 /// <summary>
78 /// 发送数据
79 /// <para>lv结构:数据的前4个字节(int),记录了数据区的长度</para>
80 /// <para>注意:数据结构根据实际使用情况而定</para>
81 /// </summary>
82 /// <param name="ip"></param>
83 /// <param name="port"></param>
84 /// <param name="data"></param>
85 public void SendData(string ip, int port, byte[] data)
86 {
87 try
88 {
89 // 创建TCP连接
90 Connect(ip, port);
91 // 取得流
92 NetworkStream networkStream = tcpClient.GetStream();
93 networkStream.ReadTimeout = 500;
94 networkStream.WriteTimeout = 500;
95
96 #region 发送数据
97 // 数据长度
98 byte[] leng = BitConverter.GetBytes(data.Length);
99 // 拼接数据头(lv结构)
100 byte[] sendArr = new byte[leng.Length + data.Length];
101 leng.CopyTo(sendArr, 0);
102 data.CopyTo(sendArr, 4);
103 // 发送数据
104 try
105 {
106 lock (networkStream)
107 {
108 networkStream.Write(sendArr, 0, sendArr.Length);
109 }
110 }
111 catch { }
112 #endregion
113
114 // 接收数据
115 Thread.Sleep(50);
116
117 #region 接收数据
118 // 接收数据储存
119 List<byte> list = new List<byte>();
120 // 数据区总长度
121 byte[] lenArr = new byte[4];
122 networkStream.Read(lenArr, 0, lenArr.Length);
123 int dataLen = BitConverter.ToInt32(lenArr, 0);
124 // 读取数据区数据
125 int total = 0;
126 // 每次读取的数据大小
127 int arrLen = 1024;
128 while (true)
129 {
130 // 读取数据
131 byte[] arr = new byte[arrLen];
132 int len = networkStream.Read(arr, 0, arr.Length);
133 for (int i = 0; i < len; i++)
134 {
135 list.Add(arr[i]);
136 }
137 // 判断数据的是否读取完成
138 total += len;
139 if (dataLen - total <= 0)
140 {
141 break;
142 }
143 if (dataLen - total < arrLen)
144 {
145 arrLen = dataLen - total;
146 }
147 Thread.Sleep(0);
148 }
149 // 根据功能或实际情况处理接收的数据
150 byte[] receiveData = list.ToArray();
151 DealData(ip, port, receiveData);
152 #endregion
153 }
154 catch
155 {
156 throw;
157 }
158 finally
159 {
160 Close();
161 }
162 }
163
164 /// <summary>
165 /// 处理数据
166 /// </summary>
167 /// <param name="ip"></param>
168 /// <param name="port"></param>
169 /// <param name="data"></param>
170 private void DealData(string ip, int port, byte[] data)
171 {
172
173 }
174 }
175 }