public class SocketTcpClient
{
public static string ErrorMsg = string.Empty;
private static Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static string _serverIp = string.Empty;
private static int _port = ;
private static int _state = ;
private static readonly int _timeout = ; private static void ClearSocket()
{
if (_socket != null)
{
_socket.Close();
}
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
} private static bool Connect()
{
try
{
if (!_socket.Connected)
{
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(_serverIp), _port);
_socket.Connect(ep);
Thread.Sleep();
}
return true; }
catch (System.Exception ex)
{
ClearSocket();
ErrorMsg = "网络错误!原因:" + ex.Message;
return false;
}
} private static bool Send(byte[] byteArray)
{
bool bConnect = _socket.Connected;
if (!bConnect)
bConnect = Connect(); if (bConnect)
{
try
{
var numberOfBytesSent = _socket.Send(byteArray);
if (numberOfBytesSent == )
{
ClearSocket();
ErrorMsg = "网络错误!原因:发送时对方关闭socket连接";
return false;
}
return true;
}
catch (System.Exception ex)
{
ClearSocket();
ErrorMsg = "网络错误!原因:" + ex.Message;
return false;
}
}
return false;
} private static bool Receive(ref byte[] byteArray)
{
bool bConnect = _socket.Connected;
if (!bConnect)
bConnect = Connect(); if (bConnect)
{
MemoryStream ms = new MemoryStream();
byte[] readBuffer = new byte[*]; do
{
var numberOfBytesRead = ;
try
{
numberOfBytesRead = _socket.Receive(readBuffer);
}
catch (System.Exception ex)
{
ClearSocket();
ErrorMsg = "网络错误!原因:" + ex.Message;
return false;
} //对方关闭socket连接,上面的Read函数据阻塞取消,收到数据为0
if (numberOfBytesRead == )
{
ClearSocket();
ErrorMsg = "网络错误!原因:接收时对方关闭socket连接";
return false;
} //增加接收到的数据,并转化为MemoryStream
ms.Write(readBuffer, , numberOfBytesRead); } while (_socket.Connected && _socket.Available > ); byteArray = ms.ToArray();
return true;
}
return false;
} private static void RunWorkThread(object stateInfo)
{
DateTime dt = (DateTime) stateInfo;
while (true)
{
Thread.Sleep();
TimeSpan ts = DateTime.Now - dt;
if (_state == )
{
if (ts.Seconds > _timeout)
{
ClearSocket();
_state = ;
break;
}
}
else
{
break;
}
}
} private static bool SysCall(byte[] dataRequest, ref byte[] dataResponse)
{
_state = ;
ThreadPool.QueueUserWorkItem(RunWorkThread, DateTime.Now); bool bResult = false;
if (Send(dataRequest))
{
bResult = Receive(ref dataResponse);
} if (_state == )
{
ErrorMsg = "超时错误!";
}
else
{
_state = ;
}
return bResult;
} /// <summary>
/// 同步传输
/// </summary>
/// <param name="controller"></param>
/// <param name="action"></param>
/// <param name="msg">utf-8</param>
/// <returns></returns>
public static string SyncCallMessage(string controller, string action, string msg)
{
byte[] msgRequest = Encoding.UTF8.GetBytes(controller + " " + action + " " + msg + Environment.NewLine);
byte[] result = null;
string msgResult = null; //同步调用远程方法
bool bSuccess = SysCall(msgRequest, ref result);
if (bSuccess)
{
msgResult = Encoding.UTF8.GetString(result);
}
return msgResult;
} public static void SetServerIp(string serverIp, int port)
{
_serverIp = serverIp;
_port = port;
ClearSocket();
}
}
public static class JsonConvert
{
public static string ToJsonEx(this object dto)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(dto);
} public static T FromJsonEx<T>(this string json)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
}
}
主要用在Pda开发数据通信方式,当然在Pda上用webrequest,拿到json解析也可以,以上Socket请求服务是同步的,如果需要稍微改善下,异步接收数据,那么服务器可以做到推送消息。