新增TCP扩展

This commit is contained in:
zgf committed 2023-08-11 15:17:28 +08:00
1 parent 514d6f5255
commit f119665d29
26 files changed
+2457 -34

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace HHWMS.Web
{
public class SyncSocketClient
{
private static SyncSocketClient instance = null;
/// <summary>
/// 客户端连接Socket
/// </summary>
private Socket clientSocket;
/// <summary>
/// 连接点
/// </summary>
private IPEndPoint hostEndPoint;
/// <summary>
///
/// </summary>
/// <param name="hostName">服务端地址{IP地址}</param>
/// <param name="port">端口号</param>
public SyncSocketClient(String hostName, Int32 port)
{
//IPAddress address = null;
//if (!String.IsNullOrEmpty(hostName))
//{
// IPAddress.TryParse(hostName, out address);
//}
//else
//{
// IPHostEntry host = Dns.GetHostEntry(hostName);
// IPAddress[] addressList = host.AddressList;
// foreach (IPAddress ad in addressList)
// {
// if (ad.AddressFamily == AddressFamily.InterNetwork)
// {
// address = ad;
// break;
// }
// }
//}
//this.hostEndPoint = new IPEndPoint(address, port);
//this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
/// <summary>
/// 连接服务端
/// </summary>
public string Send(String hostName, Int32 port, string message)
{
string receiveMsg = "";
IPAddress address = null;
if (!String.IsNullOrEmpty(hostName))
{
IPAddress.TryParse(hostName, out address);
}
else
{
IPHostEntry host = Dns.GetHostEntry(hostName);
IPAddress[] addressList = host.AddressList;
foreach (IPAddress ad in addressList)
{
if (ad.AddressFamily == AddressFamily.InterNetwork)
{
address = ad;
break;
}
}
}
IPEndPoint hostPoint = new IPEndPoint(address, port);
using (clientSocket = new Socket(hostPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
clientSocket.Connect(hostPoint);
clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
byte[] sendMsg = Encoding.GetEncoding("GBK").GetBytes(message);
clientSocket.Send(sendMsg);
//设置超时
//clientSocket.ReceiveTimeout = 5000;
byte[] receiveByte = new byte[1024];
int count = 0;
try
{
count = clientSocket.Receive(receiveByte, receiveByte.Length, 0);//接受数据
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "接受信息超时!");
}
receiveMsg += Encoding.GetEncoding("GBK").GetString(receiveByte, 0, count);//转换为GBK格式的字符串
receiveMsg = receiveMsg.Replace("\n\r", "");
Console.WriteLine("接受信息:" + receiveMsg);
}
return receiveMsg;
}
/// <summary>
/// TCP通信服务实例
/// </summary>
public static SyncSocketClient Instance
{
get
{
if (instance == null)
{
instance = new SyncSocketClient("", 3666);
}
return instance;
}
}
}
}