المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Another TCP Issue



C# Programming
09-21-2009, 09:30 PM
Hey guys

I'm trying to communicate with an external device(proximity card reader) over TCP/IP.

At the moment im able to send the device a packet and receive a reply from the device. The problem is, that when i try to send a second packet I get an IOException at NetworkStream.Write(Buffer, 0, Buffer.Length); stating "Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host."

This makes no sense to me, the device does not close the connection, I am 100% sure of that.

Here is the code of my test program.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace NewBadgerTest
{
public partial class Form1 : Form
{
TcpClient BadgerConnection;

public Form1()
{
InitializeComponent();

try
{
BadgerConnection = new TcpClient();
BadgerConnection.Connect(IPAddress.Parse("10.0.0.100"), 1111);

this.Text += " - Connected";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error while connecting", MessageBoxButtons.OK, MessageBoxIcon.Error);
}


}

private void button1_Click(object sender, EventArgs e)
{
if (BadgerConnection.Connected)
{
//
// This packet commands the device to return its version number
byte[] Buffer = new byte[]
{
161,
15,
89,
1,
89,
3,
102
};

NetworkStream ns = BadgerConnection.GetStream();
ns.Write(Buffer, 0, Buffer.Length);
ns.Flush();

string Reply = GetReply(BadgerConnection.GetStream());

MessageBox.Show(Reply);
}
}

public string GetReply(NetworkStream ns)
{
StringBuilder result = new StringBuilder();

try
{
byte[] Buffer = new byte[1024];

while (true)
{
if (ns.CanRead)
{
int numberOfBytesRead = 0;

// Incoming message may be larger than the buffer size.
while (ns.DataAvailable)
{
numberOfBytesRead = ns.Read(Buffer, 0, Buffer.Length);

result.AppendFormat("{0}", Encoding.ASCII.GetString(Buffer, 0, numberOfBytesRead));
}

if (result.Length > 0)
{
break;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

return result.ToString();
}
}
}

For simplicity's sake the part where a reply is read is not in a different thread although when I do it like that the result is the same.

Can someone please shed some light on what might be the cause of this problem? Cause I'm running out of ideas and things to try.

Thanks

Harvey Saayman - South Africa
Software Developer
.Net, C#, SQL
you.suck = (you.Occupation == jobTitles.Programmer && you.Passion != Programming)
1000100 1101111 1100101 1110011 100000 1110100 1101000 1101001 1110011 100000 1101101 1100101 1100001 1101110 100000 1101001 1101101 100000 1100001 100000 1100111 1100101 1100101 1101011 111111