代码地址:https://gitee.com/qq28069933146_admin/csharp_networkprotocol_research
视频演示: C#-TCP与UDP通讯示例演示
一、TCPClinet知识点
1、创建TCPClient客户端发送消息示例:
/// <summary>
/// 发送消息-未做粘包和拆包处理
/// </summary>
/// <param name="hostname">Ip</param>
/// <param name="port">端口</param>
/// <param name="msg">数据流</param>
/// <returns></returns>
public ResultData_TCP ConnectAndSendMsg_Nohandle(string hostname, int port, string msg)
{
ResultData_TCP resultData_TCP = new ResultData_TCP();
try
{
_tcpClient = new TcpClient(hostname, port);
byte[] data = System.Text.Encoding.ASCII.GetBytes(msg);
NetworkStream stream = _tcpClient.GetStream(); // 获取当前数据流
stream.Write(data, 0, data.Length); // 写入
stream.Flush();
stream.Close(); // 关闭流
resultData_TCP = new ResultData_TCP()
{
ResultCode = 1,
ResultMsg = "发送成功!"
};
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("参数无效;错误内容: ", e.HResult, ",", e.Message)
};
} // 参数无效(当将 null 引用传递到不接受其作为有效参数的方法时引发的异常。)
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("网络异常,套接字错误;错误内容: ", e.HResult, ",", e.Message)
};
} // 套接字错误(发生套接字错误时引发的异常。)
catch (Exception ex)
{
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("发生错误;错误内容: ", ex.HResult, ",", ex.Message),
};
} // 其他错误信息
return resultData_TCP;
}
- 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.
2、创建TcpListener监听TCPClient(线程-Net Framework):
/// <summary>
/// 开启/关闭监听-控制线程
/// </summary>
private void btnOpenCloseThread_Click(object sender, EventArgs e)
{
try
{
if (btnOpenCloseThread.Text == "开启监听-控制线程") // 开启监听
{
// 检查地址
if (!CheckServerUrl())
{
return;
}
IPHostEntry ipInfo = Dns.Resolve("127.0.0.1"); // 主机信息
IPAddress[] ipList = ipInfo.AddressList; // IP数组
IPAddress localAddr = ipList[0]; // IP
int port = int.Parse(txtPort.Text);
_listenter = _TCPHelper.TcpListener_Start(localAddr, port);
_listenter.Start(); // 开始监听
thListener = new Thread(new ThreadStart(Run)); //定义线程进行监听
thListener.IsBackground = true;
thListener.Start(); //线程启动
btnOpenCloseThread.Text = "关闭监听-控制线程";
btnOpenCloseThread.BackColor = Color.FromArgb(128, 255, 128);
}
else // 关闭监听
{
if (thListener != null)
{
//thListener.Interrupt();
_listenter.Stop();
}
btnOpenCloseThread.Text = "开启监听-控制线程";
btnOpenCloseThread.BackColor = Color.FromArgb(255, 128, 128);
}
}
catch (Exception ex)
{
btnOpenCloseThread.Text = "开启监听-控制线程";
btnOpenCloseThread.BackColor = Color.FromArgb(255, 128, 128);
ShowLog($"开启/关闭监听失败,错误信息: {ex.Message}");
}
}
/// <summary>
/// 监听-线程方法
/// </summary>
private void Run()
{
while (true)
{
try
{
using TcpClient client = _listenter.AcceptTcpClient(); // 接受一个Client
NetworkStream stream = client.GetStream(); // 获取网络流
// 接收信息
byte[] buffer = new byte[client.ReceiveBufferSize]; // 存储接收到的流
stream.Read(buffer, 0, buffer.Length); // 读取网络流中的数据
string dataStr = System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length);
Console.WriteLine("Received: {0}", dataStr);
// 发回回复
byte[] msg = System.Text.Encoding.ASCII.GetBytes(dataStr);
stream.Write(msg, 0, msg.Length);
string msgStr = System.Text.Encoding.ASCII.GetString(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", msgStr);
stream.Close(); // 关闭流
client.Close(); // 关闭Client
if (string.IsNullOrEmpty(dataStr)) // 展示
{
this.Invoke(new Action(() =>
{
txtInfo.Text += string.Concat("\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "->", "线程监听_接收到内容,内容为:", dataStr);
}));
}
}
catch (Exception ex)
{
this.Invoke(new Action(() =>
{
txtInfo.Text += string.Concat("\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "->", "线程监听出错,错误信息:", ex.Message);
}));
}
Thread.Sleep(500);
}
}
- 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.
3、创建TcpListener监听TCPClient(线程+委托方法-Net 5):
/// <summary>
/// 创建并开启TCP侦听
/// </summary>
/// <param name="localAddr">地址</param>
/// <param name="port">端口</param>
/// <param name="callback">委托方法</param>
/// <returns></returns>
public void TcpListener_Start(IPAddress localAddr, int port, Action<ResultData_TCP>? callback)
{
try
{
if (localAddr != null)
{
_server = new TcpListener(localAddr, port);
}
else
{
_server = new TcpListener(port);
}
_server.Start();
cts = new CancellationTokenSource();
Task.Run(() => ThreadCode(cts.Token, callback));
}
catch (SocketException e)
{
Console.WriteLine("Socket异常,错误信息: {0}", e.HResult + "_" + e.Message);
ResultData_TCP state = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("SocketException:", e.HResult, ",", e.Message)
};
callback?.Invoke(state);
}
catch (Exception ex)
{
Console.WriteLine("接收出错,错误信息: {0}", ex.HResult + "_" + ex.Message);
ResultData_TCP state = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("出错,错误内容: ", ex.HResult, ",", ex.Message)
};
callback?.Invoke(state);
}
finally
{
}
}
/// <summary>
/// 监听
/// </summary>
/// <param name="token">线程取消的标识</param>
/// <param name="callback">委托</param>
private void ThreadCode(CancellationToken token, Action<ResultData_TCP>? callback)
{
while (!token.IsCancellationRequested)
{
try
{
TcpClient client = _server.AcceptTcpClient(); // 接受一个Client
NetworkStream stream = client.GetStream(); // 获取网络流
// 接收信息
byte[] buffer = new byte[client.ReceiveBufferSize]; // 存储接收到的流
stream.Read(buffer, 0, buffer.Length); // 读取网络流中的数据
string dataStr = System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length);
Console.WriteLine("Received: {0}", dataStr);
// 发回回复
byte[] msg = System.Text.Encoding.ASCII.GetBytes(dataStr);
stream.Write(msg, 0, msg.Length);
string msgStr = System.Text.Encoding.ASCII.GetString(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", msgStr);
stream.Close(); // 关闭流
client.Close(); // 关闭Client
ResultData_TCP state = new ResultData_TCP()
{
ResultCode = 1,
ResultMsg = "接收成功!",
ResultObject1 = dataStr, // 接收的信息
ResultObject2 = msgStr // 回复的信息
};
callback?.Invoke(state);
}
catch (SocketException e)
{
Console.WriteLine("Socket异常,错误信息: {0}", e.HResult + "_" + e.Message);
ResultData_TCP state = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("SocketException:", e.HResult, ",", e.Message)
};
callback?.Invoke(state);
}
catch (Exception ex)
{
Console.WriteLine("接收出错,错误信息: {0}", ex.HResult + "_" + ex.Message);
ResultData_TCP state = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("出错,错误内容: ", ex.HResult, ",", ex.Message)
};
callback?.Invoke(state);
}
}
_server.Stop(); // 关闭
}
/// <summary>
/// TCP监听停止
/// </summary>
public void TcpListener_Stop()
{
cts.Cancel();
}
- 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.
二、TCPHelper
/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描 述:TCP通讯相关的工具类
*│ 作 者:执笔小白
*│ 版 本:1.1
*│ 创建时间:2023-3-18 10:40:56
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空间: ZhibiXiaobai
*│ 类 名:TCPHelper
*└──────────────────────────────────────────────────────────────┘
*/
using System;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ZhibiXiaobai
{
/// <summary>
/// TCP通信帮助类
/// System.Net.Sockets类库
/// TcpListener与TcpClient
/// </summary>
public class TCPHelper
{
#region 接收端(侦听端)
/// <summary>
/// 侦听来自 TCP 网络客户端的连接
/// </summary>
TcpListener _server = null;
/// <summary>
/// 取消线程的标识
/// </summary>
private CancellationTokenSource cts;
#region 属性
/// <summary>
/// 获取或设置一个 Boolean 值,该值指定 TcpListener 是否只允许一个基础套接字来侦听特定端口。
/// </summary>
public bool TcpListener_ExclusiveAddressUse => _server.ExclusiveAddressUse;
/// <summary>
/// 获取当前 EndPoint 的基础 TcpListener
/// </summary>
public EndPoint TcpListener_LocalEndpoint => _server.LocalEndpoint;
/// <summary>
/// 获取基础网络 Socket
/// </summary>
public Socket TcpListener_Server => _server.Server;
#endregion 属性
/// <summary>
/// 创建侦听
/// </summary>
/// <param name="localAddr">地址</param>
/// <param name="port">端口</param>
/// <returns></returns>
public TcpListener TcpListener_Start(IPAddress localAddr, int port)
{
_server = new TcpListener(localAddr, port);
return _server;
}
/// <summary>
/// 创建并开启TCP侦听
/// </summary>
/// <param name="localAddr">地址</param>
/// <param name="port">端口</param>
/// <param name="callback">委托方法</param>
/// <returns></returns>
public void TcpListener_Start(IPAddress localAddr, int port, Action<ResultData_TCP>? callback)
{
try
{
if (localAddr != null)
{
_server = new TcpListener(localAddr, port);
}
else
{
_server = new TcpListener(port);
}
_server.Start();
cts = new CancellationTokenSource();
Task.Run(() => ThreadCode(cts.Token, callback));
}
catch (SocketException e)
{
Console.WriteLine("Socket异常,错误信息: {0}", e.HResult + "_" + e.Message);
ResultData_TCP state = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("SocketException:", e.HResult, ",", e.Message)
};
callback?.Invoke(state);
}
catch (Exception ex)
{
Console.WriteLine("接收出错,错误信息: {0}", ex.HResult + "_" + ex.Message);
ResultData_TCP state = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("出错,错误内容: ", ex.HResult, ",", ex.Message)
};
callback?.Invoke(state);
}
finally
{
}
}
/// <summary>
/// 监听
/// </summary>
/// <param name="token">线程取消的标识</param>
/// <param name="callback">委托</param>
private void ThreadCode(CancellationToken token, Action<ResultData_TCP>? callback)
{
while (!token.IsCancellationRequested)
{
try
{
TcpClient client = _server.AcceptTcpClient(); // 接受一个Client
NetworkStream stream = client.GetStream(); // 获取网络流
// 接收信息
byte[] buffer = new byte[client.ReceiveBufferSize]; // 存储接收到的流
stream.Read(buffer, 0, buffer.Length); // 读取网络流中的数据
string dataStr = System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length);
Console.WriteLine("Received: {0}", dataStr);
// 发回回复
byte[] msg = System.Text.Encoding.ASCII.GetBytes(dataStr);
stream.Write(msg, 0, msg.Length);
string msgStr = System.Text.Encoding.ASCII.GetString(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", msgStr);
stream.Close(); // 关闭流
client.Close(); // 关闭Client
ResultData_TCP state = new ResultData_TCP()
{
ResultCode = 1,
ResultMsg = "接收成功!",
ResultObject1 = dataStr, // 接收的信息
ResultObject2 = msgStr // 回复的信息
};
callback?.Invoke(state);
}
catch (SocketException e)
{
Console.WriteLine("Socket异常,错误信息: {0}", e.HResult + "_" + e.Message);
ResultData_TCP state = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("SocketException:", e.HResult, ",", e.Message)
};
callback?.Invoke(state);
}
catch (Exception ex)
{
Console.WriteLine("接收出错,错误信息: {0}", ex.HResult + "_" + ex.Message);
ResultData_TCP state = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("出错,错误内容: ", ex.HResult, ",", ex.Message)
};
callback?.Invoke(state);
}
}
_server.Stop(); // 关闭
}
/// <summary>
/// TCP监听停止
/// </summary>
public void TcpListener_Stop()
{
cts.Cancel();
}
/// <summary>
/// 确定是否有挂起的连接请求
/// </summary>
/// <returns></returns>
public bool TcpListener_Pending() => _server.Pending();
/// <summary>
/// 启用或禁用针对 TcpListener 实例的网络地址转换(NAT) 遍历。
/// </summary>
/// <param name="allowed">启用或禁用</param>
public void TcpListener_AllowNatTraversal(bool allowed) => _server.AllowNatTraversal(allowed);
/// <summary>
/// 接受挂起的连接请求
/// </summary>
/// <returns></returns>
public Socket TcpListener_AcceptSocket() => _server.AcceptSocket();
/// <summary>
/// 接受挂起的连接请求以作为异步操作。
/// </summary>
/// <returns></returns>
public Task<Socket> TcpListener_AcceptSocketAsync() => _server.AcceptSocketAsync();
/// <summary>
/// 接受挂起的连接请求。
/// </summary>
/// <returns></returns>
public TcpClient TcpListener_AcceptTcpClient() => _server.AcceptTcpClient();
/// <summary>
/// 接受挂起的连接请求以作为异步操作。
/// </summary>
/// <returns></returns>
public Task<TcpClient> TcpListener_AcceptTcpClientAsync() => _server.AcceptTcpClientAsync();
/// <summary>
/// 开始一个异步操作来接受一个传入的连接尝试。
/// </summary>
/// <returns></returns>
public IAsyncResult TcpListener_BeginAcceptSocket(AsyncCallback? callback, object? state) => _server.BeginAcceptSocket(callback, state);
/// <summary>
/// 异步接受传入的连接尝试,并创建新的 Socket 来处理远程主机通信。
/// </summary>
/// <param name="asyncResult"></param>
/// <returns></returns>
public Socket TcpListener_EndAcceptSocket(IAsyncResult asyncResult) => _server.EndAcceptSocket(asyncResult);
/// <summary>
/// 开始一个异步操作来接受一个传入的连接尝试。
/// </summary>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
public IAsyncResult TcpListener_BeginAcceptTcpClient(AsyncCallback? callback, object? state) => _server.BeginAcceptTcpClient(callback, state);
/// <summary>
/// 异步接受传入的连接尝试,并创建新的 TcpClient 来处理远程主机通信。
/// </summary>
/// <param name="asyncResult"></param>
/// <returns></returns>
public TcpClient TcpListener_EndAcceptTcpClient(IAsyncResult asyncResult) => _server.EndAcceptTcpClient(asyncResult);
#endregion 接收端(侦听端)
#region 发送端(客户端)
/// <summary>
/// 为 TCP 网络服务提供客户端连接
/// </summary>
TcpClient _tcpClient = new TcpClient();
#region 属性
/// <summary>
/// 是否已建立连接
/// </summary>
public bool TcpClient_Connected => _tcpClient.Connected;
/// <summary>
/// 获取已经从网络接收且可供读取的数据量
/// </summary>
public int TcpClient_Available => _tcpClient.Available;
/// <summary>
/// 获取当前连接用对象
/// </summary>
/// <returns></returns>
public Socket TcpClient_Client() => _tcpClient.Client;
/// <summary>
/// 指定 TcpClient 是否只允许一个客户端使用端口
/// </summary>
public bool TcpClient_ExclusiveAddressUse => _tcpClient.ExclusiveAddressUse;
/// <summary>
/// 获取或设置有关关联的套接字的延迟状态的信息。
/// </summary>
public LingerOption? TcpClient_LingerState => _tcpClient.LingerState;
/// <summary>
/// 获取或设置一个值,该值在发送或接收缓冲区未满时禁用延迟。
/// </summary>
public bool TcpClient_NoDelay => _tcpClient.NoDelay;
/// <summary>
/// 获取或设置接收缓冲区的大小。
/// </summary>
public int TcpClient_ReceiveBufferSize => _tcpClient.ReceiveBufferSize;
/// <summary>
/// 获取或设置在初始化一个读取操作以后 TcpClient 等待接收数据的时间量。
/// </summary>
public int TcpClient_ReceiveTimeout => _tcpClient.ReceiveTimeout;
/// <summary>
/// 获取或设置发送缓冲区的大小。
/// </summary>
public int TcpClient_SendBufferSize => _tcpClient.SendBufferSize;
/// <summary>
/// 获取或设置 TcpClient 等待发送操作成功完成的时间量。
/// </summary>
public int TcpClient_SendTimeout => _tcpClient.SendTimeout;
#endregion 属性
/// <summary>
/// 连接
/// </summary>
/// <param name="hostname">Ip</param>
/// <param name="port">端口</param>
/// <returns></returns>
public bool TcpClient_Connect(string hostname, int port)
{
_tcpClient = new TcpClient(hostname, port);
return _tcpClient.Connected;
}
/// <summary>
/// 连接
/// </summary>
/// <param name="hostname">Ip</param>
/// <param name="port">端口</param>
/// <returns></returns>
public TcpClient TcpClient_Connect2(string hostname, int port)
{
return new TcpClient(hostname, port);
}
/// <summary>
/// 连接_异步
/// </summary>
/// <param name="hostname">Ip</param>
/// <param name="port">端口</param>
/// <returns></returns>
public Task TcpClient_ConnectAsync(string hostname, int port) => _tcpClient.ConnectAsync(hostname, port);
/// <summary>
/// 连接_异步 令牌
/// </summary>
/// <param name="hostname">Ip</param>
/// <param name="port">端口</param>
/// <param name="cancellationToken">令牌</param>
/// <returns></returns>
public ValueTask TcpClient_ConnectAsync(string hostname, int port, CancellationToken cancellationToken) => _tcpClient.ConnectAsync(hostname, port, cancellationToken);
/// <summary>
/// 关闭连接
/// </summary>
public void TcpClient_Close() => _tcpClient.Close();
/// <summary>
/// 开始一个对远程主机连接_异步
/// </summary>
/// <param name="host">IP</param>
/// <param name="port">端口</param>
/// <param name="requestCallback">回调方法</param>
/// <param name="state">当操作完成时,传递给 requestCallback 委托的对象</param>
/// <returns></returns>
public IAsyncResult TcpClient_BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state) => _tcpClient.BeginConnect(host, port, requestCallback, state);
/// <summary>
/// 结束异步连接
/// </summary>
/// <param name="asyncResult"></param>
public void TcpClient_EndConnect(IAsyncResult asyncResult) => _tcpClient.EndConnect(asyncResult);
/// <summary>
/// 返回用于向远程主机读写数据的流。
/// </summary>
/// <returns></returns>
public NetworkStream TcpClient_GetStream() => _tcpClient.GetStream();
#region 接收与发送消息-未做粘包和拆包处理
/// <summary>
/// 发送消息-未做粘包和拆包处理(一般不用)
/// </summary>
/// <param name="msg">数据流</param>
/// <returns></returns>
public ResultData_TCP SendMsg_Nohandle(string msg)
{
ResultData_TCP resultData_TCP = new ResultData_TCP();
try
{
byte[] data = System.Text.Encoding.ASCII.GetBytes(msg);
NetworkStream stream = _tcpClient.GetStream(); // 获取当前数据流
stream.Write(data, 0, data.Length); // 写入
stream.Flush();
stream.Close(); // 关闭流
resultData_TCP = new ResultData_TCP()
{
ResultCode = 1,
ResultMsg = "发送成功!"
};
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("参数无效;错误内容: ", e.HResult, ",", e.Message)
};
} // 参数无效(当将 null 引用传递到不接受其作为有效参数的方法时引发的异常。)
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("网络异常,套接字错误;错误内容: ", e.HResult, ",", e.Message)
};
} // 套接字错误(发生套接字错误时引发的异常。)
catch (Exception ex)
{
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("发生错误;错误内容: ", ex.HResult, ",", ex.Message),
};
} // 其他错误信息
return resultData_TCP;
}
/// <summary>
/// 接收一次消息-未做粘包和拆包处理
/// 注:该方法不会使用;一般TCP消息使用TcpListener做接收。
/// </summary>
/// <returns></returns>
public ResultData_TCP ReceiveMsg1_Nohandle()
{
ResultData_TCP resultData_TCP = new ResultData_TCP();
try
{
byte[] data = new byte[1024]; // 接收的缓存
string responseData = string.Empty; // 接收用对象
NetworkStream stream = _tcpClient.GetStream(); // 获取流
int bytes = stream.Read(data, 0, data.Length); // 读取
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
stream.Flush();
stream.Close(); // 关闭流
resultData_TCP = new ResultData_TCP()
{
ResultCode = 1,
ResultMsg = "接收成功!",
ResultObject1 = responseData
};
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("参数无效;错误内容: ", e.HResult, ",", e.Message)
};
} // 参数无效(当将 null 引用传递到不接受其作为有效参数的方法时引发的异常。)
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("网络异常,套接字错误;错误内容: ", e.HResult, ",", e.Message)
};
} // 套接字错误(发生套接字错误时引发的异常。)
catch (Exception ex)
{
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("发生错误;错误内容: ", ex.HResult, ",", ex.Message),
};
} // 其他错误信息
return resultData_TCP;
}
/// <summary>
/// 发送消息-未做粘包和拆包处理
/// </summary>
/// <param name="hostname">Ip</param>
/// <param name="port">端口</param>
/// <param name="msg">数据流</param>
/// <returns></returns>
public ResultData_TCP ConnectAndSendMsg_Nohandle(string hostname, int port, string msg)
{
ResultData_TCP resultData_TCP = new ResultData_TCP();
try
{
_tcpClient = new TcpClient(hostname, port);
byte[] data = System.Text.Encoding.ASCII.GetBytes(msg);
NetworkStream stream = _tcpClient.GetStream(); // 获取当前数据流
stream.Write(data, 0, data.Length); // 写入
stream.Flush();
stream.Close(); // 关闭流
resultData_TCP = new ResultData_TCP()
{
ResultCode = 1,
ResultMsg = "发送成功!"
};
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("参数无效;错误内容: ", e.HResult, ",", e.Message)
};
} // 参数无效(当将 null 引用传递到不接受其作为有效参数的方法时引发的异常。)
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("网络异常,套接字错误;错误内容: ", e.HResult, ",", e.Message)
};
} // 套接字错误(发生套接字错误时引发的异常。)
catch (Exception ex)
{
resultData_TCP = new ResultData_TCP()
{
ResultCode = -1,
ResultMsg = string.Concat("发生错误;错误内容: ", ex.HResult, ",", ex.Message),
};
} // 其他错误信息
return resultData_TCP;
}
#endregion 接收与发送消息-未做粘包和拆包处理
#endregion 发送端(客户端)
}
/// <summary>
/// 信息载体
/// </summary>
public class ResultData_TCP
{
/// <summary>
/// 结果Code
/// 正常1,其他为异常;0不作为回复结果
/// </summary>
public int ResultCode { get; set; } = 0;
/// <summary>
/// 结果信息
/// </summary>
public string ResultMsg { get; set; } = string.Empty;
/// <summary>
/// 扩展1
/// </summary>
public object? ResultObject1 { get; set; } = string.Empty;
/// <summary>
/// 扩展2
/// </summary>
public object? ResultObject2 { get; set; } = string.Empty;
}
}
- 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.
- 373.
- 374.
- 375.
- 376.
- 377.
- 378.
- 379.
- 380.
- 381.
- 382.
- 383.
- 384.
- 385.
- 386.
- 387.
- 388.
- 389.
- 390.
- 391.
- 392.
- 393.
- 394.
- 395.
- 396.
- 397.
- 398.
- 399.
- 400.
- 401.
- 402.
- 403.
- 404.
- 405.
- 406.
- 407.
- 408.
- 409.
- 410.
- 411.
- 412.
- 413.
- 414.
- 415.
- 416.
- 417.
- 418.
- 419.
- 420.
- 421.
- 422.
- 423.
- 424.
- 425.
- 426.
- 427.
- 428.
- 429.
- 430.
- 431.
- 432.
- 433.
- 434.
- 435.
- 436.
- 437.
- 438.
- 439.
- 440.
- 441.
- 442.
- 443.
- 444.
- 445.
- 446.
- 447.
- 448.
- 449.
- 450.
- 451.
- 452.
- 453.
- 454.
- 455.
- 456.
- 457.
- 458.
- 459.
- 460.
- 461.
- 462.
- 463.
- 464.
- 465.
- 466.
- 467.
- 468.
- 469.
- 470.
- 471.
- 472.
- 473.
- 474.
- 475.
- 476.
- 477.
- 478.
- 479.
- 480.
- 481.
- 482.
- 483.
- 484.
- 485.
- 486.
- 487.
- 488.
- 489.
- 490.
- 491.
- 492.
- 493.
- 494.
- 495.
- 496.
- 497.
- 498.
- 499.
- 500.
- 501.
- 502.
- 503.
- 504.
- 505.
- 506.
- 507.
- 508.
- 509.
- 510.
- 511.
- 512.
- 513.
- 514.
- 515.
- 516.
- 517.
- 518.
- 519.
- 520.
- 521.
- 522.
- 523.
- 524.
- 525.
- 526.
- 527.
- 528.
- 529.
- 530.
- 531.
- 532.
- 533.
- 534.
- 535.
- 536.
- 537.
- 538.
- 539.
- 540.
- 541.
- 542.
- 543.
- 544.
- 545.
- 546.
- 547.
- 548.
- 549.
- 550.
- 551.
- 552.
- 553.
- 554.
- 555.
- 556.
- 557.
- 558.
- 559.
- 560.
- 561.
- 562.
- 563.
- 564.
- 565.
- 566.
- 567.
- 568.
- 569.
- 570.
- 571.
- 572.
- 573.
- 574.
- 575.
- 576.
- 577.
- 578.
- 579.
- 580.
- 581.
- 582.
- 583.
- 584.
- 585.
- 586.
作者:꧁执笔小白꧂