using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Us.Standard.UsTools;
namespace Us.Core.FrameWork.UsTools
{
public class TSocketClientHelper
{
private IPAddress serverIP = null;
private int port = 0;
private System.Net.Sockets.Socket socket = null;
private bool _connected = false;
/// <summary>
/// 构造方法
/// </summary>
/// <param name="ip">服务器IP</param>
/// <param name="port">服务器端口</param>
public TSocketClientHelper(string ip, int port)
{
this.serverIP = IPAddress.Parse(ip);
this.port = port;
}
public bool connected()
{
return socket.Connected;
}
public Boolean SendData(byte[] sdata)
{
if (null == socket)
{
throw new Exception("Socket对象为空");
}
if (null == sdata)
{
return false;
}
try
{
socket.Send(sdata);
return true;
}
catch
{
_connected = false;
return false;
}
}
//接受数据
public byte[] ReceiveData(ref int len)
{
byte[] resBytes = new byte[100];
try
{
len = socket.Receive(resBytes, 100, 0);
}
catch
{
len = -1;
_connected = false; ;
}
return resBytes;
}
public byte[] ReceiveData1(Int32 length,ref int len)
{
byte[] resBytes = new byte[length];
try
{
len = socket.Receive(resBytes, length, 0);
}
catch
{
len = -1;
_connected = false; ;
}
return resBytes;
}
public Boolean Connect()
{
socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.ReceiveTimeout = 20000; var result = socket.BeginConnect(serverIP, port, null, null); _connected = result.AsyncWaitHandle.WaitOne(5000); socket.EndConnect(result);
return _connected;
}
catch
{
_connected = false;
return false;
}
}
public void disConnect()
{
try
{
if (null != socket)
{
if (socket.Connected)
socket.Shutdown(SocketShutdown.Both);
//关闭SOCKET
socket.Close();
}
}
catch (Exception e)
{
UsKFileLogTools.AddLog("ip=" + serverIP,e);
}
}
}
}