using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using ZLPlugin_LisPacs_MR.Domain.Units;
namespace ZLPlugin_LisPacs_MR
{
///
/// socket客户端
///
public class SocketClient
{
public static string Message = null;//接收消息
///
/// 客户端socket
///
public Socket _ClientSocket = null;
///
/// IP地址
///
public string ipAddress = string.Empty;
///
/// IP端口
///
public int Port;
///
/// 接收线程
///
private Thread threadReceive;
///
/// 是否运行
///
private bool IsRun = false;
///
/// 远端地址
///
private string remoteEndPoint;
///
/// 本端地址
///
private string LocalEndPoint;
///
/// 客户端
///
///
///
public SocketClient(string ip,int Port)
{
_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_ClientSocket.ReceiveTimeout = 2000;
this.ipAddress = ip;
this.Port = Port;
Start();
}
///
/// 启动连接服务端
///
public void Start()
{
try
{
_ClientSocket.Connect(new IPEndPoint(IPAddress.Parse(this.ipAddress), this.Port));//通过IP和端口号来定位一个所要连接的服务器端
//客户端网络结点号
remoteEndPoint = _ClientSocket.RemoteEndPoint.ToString();
LocalEndPoint = _ClientSocket.LocalEndPoint.ToString();
Log.Info($"远端地址:{remoteEndPoint} 本端地址:{LocalEndPoint}");
//threadReceive = new Thread(Receive);
//threadReceive.IsBackground = true;
//threadReceive.Start();
/* remoteEndPoint = _ClientSocket.RemoteEndPoint.ToString();
LocalEndPoint = _ClientSocket.LocalEndPoint.ToString();
//Console.WriteLine($"远端地址:{remoteEndPoint} 本端地址:{LocalEndPoint}");
threadReceive = new Thread(Receive);
threadReceive.IsBackground = true;
threadReceive.Start();*/
IsRun = true;
}
catch (Exception ex)
{
Log.Info("平台插件未运行!请启动插件。", true);
Log.Info(ex.Message, true);
Log.Info(ex.StackTrace, true);
}
}
///
/// 接收服务端发送过来的消息
///
public void Receive()
{
//string message = "";
try
{
byte[] TempData = new byte[1024 * 10];
while (IsRun)
{
//传递一个byte数组,用于接收数据。length表示接收了多少字节的数据
int length = _ClientSocket.Receive(TempData);
if (length == 0)
{
IsRun = false;
//Console.WriteLine("服务器断开链接");
break;
}
else
{
Message = Encoding.Default.GetString(TempData, 0, length);//只将接收到的数据进行转化
//Console.WriteLine($"远端地址:{remoteEndPoint} 本端地址:{LocalEndPoint} 获取到的数据:{message}");
//Log.Info("出参:" + Message);
}
}
}
catch (Exception ex)
{
//Log.Info("95478");
Log.Info(ex.Message);
//Log.Info(ex.StackTrace, true);
}
}
///
/// 发送消息到服务端
///
///
///
public int Send(string data)
{
Message = null;
return _ClientSocket.Send(Encoding.Default.GetBytes(data));
}
public void Close()
{
IsRun = false;
if (threadReceive != null)
{
try
{
threadReceive.Interrupt();
Thread.Sleep(200);
}
catch (Exception ex)
{
Log.Info(ex.Message, true);
Log.Info(ex.StackTrace, true);
}
threadReceive = null;
}
if (_ClientSocket != null)
{
_ClientSocket.Close();
}
}
}
}