System.IO.IOException:无法从传输连接读取数据,主机强制关闭现有连接

时间:2017-03-15 02:39:03

标签: c# sockets openiso8583.net

我正在尝试构建ISO8583消息,并且必须使用TCP / IP将其发送到服务器,我应该从服务器获得响应。但是我收到了错误。请帮帮我。

private static Iso8583 NetworkSend(string ip, int port, Iso8583 msg)
{

    // We're going to use a 2 byte header to indicate the message length
    // which is not inclusive of the length of the header
    var msgData = new byte[msg.PackedLength + 2];

    // The two byte header is a base 256 number so we can set the first two bytes in the data 
    // to send like this
    msgData[0] = (byte)(msg.PackedLength % 256);
    msgData[1] = (byte)(msg.PackedLength / 256);

    // Copy the message into msgData
    Array.Copy(msg.ToMsg(), 0, msgData, 2, msg.PackedLength);

    // Now send the message.  We're going to behave like a terminal, which is 
    // connect, send, receive response, disconnect
    var client = new TcpClient();
    var endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
    client.Connect(endPoint);
    var stream = client.GetStream();

    // Send the packed message
    stream.Write(msgData, 0, msgData.Length);

    // Receive the response

    // First we need to get the length of the message out of the socket
    var lengthHeader = new byte[2];
    stream.Read(lengthHeader, 0,2);//this line im getting error

    // Work out the length of the incoming message
    var rspLength = lengthHeader[0] * 256 + lengthHeader[1];
    var rspData = new byte[rspLength];

    // Read the bytes off the network stream
    stream.Read(rspData, 0, rspLength);

    // Close the network stream and client
    stream.Close();
    client.Close();

    // Parse the data into an Iso8583 message and return it
    var rspMsg = new Iso8583();

    rspMsg.Unpack(rspData, 0);
    return rspMsg;
}

0 个答案:

没有答案