/*CustomerTimer*/
public class CustomerTimer
{
public DateTime(Duetime(double time_ms){return DateTime.Now.AddMilliseconds(time_ms);}
public bool Timeout(DateTime duetime){
TimeSpan diff=duetime-DateTime.Now;if(diff.TotalSeconds>0)return false;elsereturn true;}
public voidDelay(int time_ms){
Thread.Sleep(time_ms);}}
public static CustomerTimer checkTime;/* connect*/
public bool SocketConnect()
Socket remoteSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
remoteSocket.SendTimeout =2000;
remoteSocket.ReceiveTimeout =2000;
IAsyncResult ar = remoteSocket.BeginConnect(IPAddress.Parse(equip_ip), equip_port, null, null);
DateTime connDueTime = checkTime.Duetime(T3);while(!ar.IsCompleted){if(checkTime.Timeout(connDueTime)){break;}}return remoteSocket.Connected;}/*send remote ip and address message*/
public bool SendMsg(byte[] sendMsg){int waitTime=3;int sendPoint=0;int curSend=0;
bool result=false;while(waitTime>0){if(sendPoint<sendMsg.Length){
curSend=remoteSocket.Send(sendMsg,sendPoint,sendMsg.Length-sendPoint,SocketFlags.None);
sendPoint +=curSend;}else{
result = true;break;}
waitTime--;
Thread.Sleep(100);}
reture result;}/*receive data*/
public bool ReceiveData(Socket remoteSocket){int count,smgLength;
bool isReceived=false;
count=remoteSocket.Available;
recTimeout=checTime.DueTime(5000);while(count<=4){
checkTime.Delay(100);
count=remoteSocket,Available;if(checkTime.Timeout(recTimeout)){return isReceived;}if(isAppClosed)return isReceived;}
isReceived=true;return isReceived;}
异步通讯
发送要知道remote IPaddress和Port,接收要知道local端Port;
发送端发送后可以立即关闭
/*receive data from local ip and port */
private voidWaitData(){
Socket localSocket = new new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any,5004);
localSocket.Bind(localEndPoint);
localSocket.Listen(150);while(true){int count, msgLength;
count = localSocket.Available;
recTimeout = checkTime.Duetime(5000);while(count<=4){
checkTime.Delay(100);
count = localSocket.Available;if(checkTime.Timeout(recTimeout)){break;}}
byte[] receiveBytes=new byte[count];
receiveBytes.Receive(receiveBytes);....}}/*send data to remote ip and port */
private voidSendMessage(){SocketConnect();...if(SendMsg(byte[] sendMsg)){
remoteSocket.Shutdown(SocketShutdown.Send);
remoteSocket.close()}...}