private void TCPOnStart(AsyncPerformer performer, ref object userState) { if (performer.userSocket == null) { performer.userSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); performer.userSocket.Bind(new IPEndPoint(IPAddress.Parse(LocalIP), performer.usePort));//指定本机地址及端口 performer.userSocket.Connect(DestinationIP.Text, int.Parse(DestinationPort.Text)); } else if (!performer.userSocket.Connected) { performer.userSocket.Bind(new IPEndPoint(IPAddress.Parse(LocalIP), performer.usePort));//指定本机地址及端口 performer.userSocket.Connect(DestinationIP.Text, int.Parse(DestinationPort.Text)); } performer.userSocket.SendTimeout = (int)(0.5 * performer.Interval); performer.userSocket.ReceiveTimeout = performer.userSocket.SendTimeout; }
private void TCPOnStop(AsyncPerformer performer, ref object userState) { if (performer.userSocket != null) { try { //IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(LocalIP), performer.usePort); //TcpListener tcpListener = new TcpListener(endPoint); //tcpListener.Stop(); performer.userSocket.Close(); } catch { } } }
private void Connectbutton_Click(object sender, EventArgs e) { //asyncClientlist = new List<AsyncTcpClient>(); //for (int i = 0; i < int.Parse(ConnectNum.Text); i++) //{ // asyncClientlist.Add(new AsyncTcpClient(DestinationIP.Text, int.Parse(DestinationPort.Text))); //} //foreach (AsyncTcpClient atc in asyncClientlist) //{ // atc.Connect(); //} asyncPerformerlist = new List <AsyncPerformer>(); for (int i = 0; i < int.Parse(ConnectNum.Text); i++) { AsyncPerformer apf = new AsyncPerformer(); apf.Timeout = 5 * uint.Parse(COMinterval.Text); apf.Interval = int.Parse(COMinterval.Text); apf.OnStart += TCPOnStart; apf.OnStop += TCPOnStop; apf.OnAsyncWork += TCPOnAsyncWork; apf.usePort = int.Parse(listenPort.Text) + i;//缓兵之计,监听端口的关闭问题 if (readORwrite.SelectedIndex == 1) { apf.readFlag = true; } if (readORwrite.SelectedIndex == 2) { apf.writeFlag = true; } apf.Start(); asyncPerformerlist.Add(apf); } debug_text.Clear(); testnum = 0; successnum = 0; timer1.Start(); Connectbutton.Enabled = false; Disconnectbutton.Enabled = true; }
private void TCPOnAsyncWork(AsyncPerformer apf, ref bool reqNewThread, ref object userState) { if (!apf.userSocket.Connected) { //apf.Start(); } byte[] readbyte = { 0x01, 0x01, 0x00, 0x00, 0x00, 0x04, 0x3D, 0xC9 }; byte[] readbyte2 = { 0x01, 0x01, 0x00, 0x00, 0x00, 0x04, 0x3D, 0xC9 }; byte[] writebyte = { 0x01, 0x05, 0x00, 0x10, 0x00, 0x00, 0xCC, 0x0F }; if (apf.readFlag) { apf.userSocket.Send(readbyte); byte[] receive = new byte[6]; apf.userSocket.Receive(receive); if (receive[1] == 0x01) { apf.readsuccess = true; } else { apf.readsuccess = false; } } if (apf.writeFlag) { apf.userSocket.Send(writebyte); byte[] receive = new byte[8]; apf.userSocket.Receive(receive); if (receive[1] == 0x05) { apf.writesuccess = true; } else { apf.writesuccess = false; } } }