public class AsyncTCP
{
readonly S7_telegrasm s7 = new S7_telegrasm();
public Socket socket;
/// <summary>
/// 连接
/// </summary>
public void Connect(string ip, string port)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress IPA = IPAddress.Parse(ip);
IPEndPoint iep = new IPEndPoint(IPA, int.Parse(port));
socket.BeginConnect(iep, new AsyncCallback(ConnectCallbackj), socket);
byte[] send;
try
{
//cotp的发送接收
send = s7.Cotp();
socket.BeginSend(send, 0, send.Length, 0, new AsyncCallback(tellCallback), socket); //建立连接时这里报错了
Thread.Sleep(100);
byte[] cotp = new byte[22];
socket.BeginReceive(cotp, 0, cotp.Length, 0, new AsyncCallback(askCallback), socket);
Thread.Sleep(100);
//通信建立的发送接收
send = s7.Comm();
socket.BeginSend(send, 0, send.Length, 0, new AsyncCallback(tellCallback), socket);
Thread.Sleep(100);
byte[] S7comm = new byte[27];
socket.BeginReceive(S7comm, 0, S7comm.Length, 0, new AsyncCallback(askCallback), socket);
Thread.Sleep(100);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Connect回调函数
/// </summary>
void ConnectCallbackj(IAsyncResult iar)
{
try
{
Socket client = (Socket)iar.AsyncState;
client.EndConnect(iar);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private void askCallback(IAsyncResult iar)
{
try
{
Socket ask = (Socket)iar.AsyncState;
int bytesSent = ask.EndSend(iar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
ask.Shutdown(SocketShutdown.Both);
ask.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void tellCallback(IAsyncResult iar)
{
try
{
Socket tell = (Socket)iar.AsyncState;
int bytesSent = tell.EndSend(iar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
tell.Shutdown(SocketShutdown.Both);
tell.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
/// <summary>
/// 发送数据
/// </summary>
public void Send(Socket handler, byte[] byteSend)
{
handler.BeginSend(byteSend, 0, byteSend.Length, 0, new AsyncCallback(SendCallback), handler);
}
private void SendCallback(IAsyncResult iar)
{
try
{
Socket handler = (Socket)iar.AsyncState;
int bytesSent = handler.EndSend(iar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
/// <summary>
/// 接收数据
/// </summary>
public void Receive(Socket client,byte[] byteRead)
{
try
{
if (byteRead.Length > 0)
{
client.BeginReceive(byteRead, 0, byteRead.Length, 0, new AsyncCallback(ReceiveCallback), client);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void ReceiveCallback(IAsyncResult iar)
{
try
{
Socket handler = (Socket)iar.AsyncState;
int bytesSent = handler.EndSend(iar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
我本想建立连接时将两个报文发送过去,但是在报文发送哪里出了问题,连接上了,发不过去