using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace TestDemo
{
///
/// 处理TCP数据的类(服务端)
///
public class TcpService
{
///
/// TCP监听对象
///
private TcpListener tcpListener;
///
/// 创建TCP监听
///
public void CreateListener(int port)
{
// 监听对象
tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
// 独立线程监听
Thread thread = new Thread(StartListener);
thread.Start();
}
///
/// 开始监听
///
private void StartListener()
{
while (true)
{
try
{
// TCP监听
TcpClient tcpClient = tcpListener.AcceptTcpClient();
// 多线程处理数据
Thread thread = new Thread(new ParameterizedThreadStart(delegate { DealTcpData(tcpClient); }));
thread.Start();
}
catch (Exception ex)
{
// 错误日志
Log.WriteError(ex);
}
}
}
///
/// 处理TCP数据
/// lv结构:数据的前4个字节(int),记录了数据区的长度
/// 注意:数据结构根据实际使用情况而定
///
private void DealTcpData(TcpClient tcpClient)
{
try
{
if (tcpClient.Connected)
{
// 取得流
NetworkStream networkStream = tcpClient.GetStream();
networkStream.ReadTimeout = 500;
networkStream.WriteTimeout = 500;
#region 接收数据
// 接收数据储存
List<byte> list = new List<byte>();
// 数据区总长度
byte[] lenArr = new byte[4];
networkStream.Read(lenArr, 0, lenArr.Length);
int dataLen = BitConverter.ToInt32(lenArr, 0);
// 读取数据区数据
int total = 0;
// 每次读取的数据大小
int arrLen = 1024;
while (true)
{
// 读取数据
byte[] arr = new byte[arrLen];
int len = networkStream.Read(arr, 0, arr.Length);
for (int i = 0; i < len; i++)
{
list.Add(arr[i]);
}
// 判断数据的是否读取完成
total += len;
if (dataLen - total <= 0)
{
break;
}
if (dataLen - total < arrLen)
{
arrLen = dataLen - total;
}
Thread.Sleep(0);
}
// 根据功能或实际情况处理接收的数据
byte[] receiveData = list.ToArray();
#endregion
#region 发送数据
// 取得数据
// 根据功能或实际情况做成需要发送的数据
byte[] dataArr = new byte[] { 0x01, 0x02, 0x03, 0x04 }; // 测试数据
if (dataArr != null)
{
// 数据长度
byte[] lengArr = BitConverter.GetBytes(dataArr.Length);
// 拼接数据头(lv结构)
byte[] sendArr = new byte[lengArr.Length + dataArr.Length];
lengArr.CopyTo(sendArr, 0);
dataArr.CopyTo(sendArr, 4);
// 发送数据
try
{
lock (networkStream)
{
networkStream.Write(sendArr, 0, sendArr.Length);
}
}
catch { }
}
#endregion
}
}
catch (Exception ex)
{
// 错误日志
Log.WriteError(ex);
}
finally
{
// 判断TCP对象是否连接
if (tcpClient != null)
{
JudgeTcpConnection(tcpClient);
}
}
}
///
/// 判断TCP对象是否连接
///
private void JudgeTcpConnection(TcpClient tcpClient, int timeout = 3)
{
try
{
DateTime time = DateTime.Now;
while (true)
{
// 超时时间判断
if (time.AddSeconds(timeout) < DateTime.Now)
{
break;
}
// 连接状态判断
if (!tcpClient.Connected)
{
break;
}
else
{
bool flag = tcpClient.Client.Poll(1000, SelectMode.SelectRead);
if (flag)
{
break;
}
}
Thread.Sleep(0);
}
}
catch (Exception ex)
{
// 错误日志
Log.WriteError(ex);
}
finally
{
// 关闭连接
tcpClient.Close();
}
}
}
}
原文地址 https://www.cnblogs.com/smartnn/p/16635584.html