Teetrinker
Teetrinker

Reputation: 850

Sockets on Windows - did I miss something in my program?

Thanks for reading and answering in advance!

I wrote a simple C# program that connects via sockets with a third-party tool. Whenever I send a string longer than 1024 characters, the third-party software throws an error. Now I am trying to find out if this is a problem of my socket code or one of the other software (EnergyPlus).

It is only a few lines of code, and if anyone has suggestions, they would be highly appreciated!

using System.IO;
using System.Net;
using System.Net.Sockets;
...
private int port = 1410;
private TcpListener listener;
private Stream s;
private StreamReader sr;
private StreamWriter sw;
private Socket soc;
...

Here it really starts:

listener = new TcpListener(port);
listener.Start();
soc = listener.AcceptSocket();

// now, the other program connects

soc.SetSocketOption(SocketOptionLevel.Socket,
        SocketOptionName.ReceiveTimeout, 10000);

s = new NetworkStream(soc);

sr = new StreamReader(s);
sw = new StreamWriter(s);
sw.AutoFlush = true; // enable automatic flushing

sw.WriteLine("more or less than 1024 characters");

...

This is the code I use. Anything I forgot? Anything I should take care of? I am glad about any suggestions.

The error I get from E+ is the following:

ExternalInterface: Socket communication received error value " 1" at time = 0.00 hours.
ExternalInterface: Flag from server " 0".

Upvotes: 2

Views: 361

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063774

Yu need to look at the specification defined by EnergyPlus; any socket communication needs rules. There are two obvious options here:

  1. you aren't following the rules (maybe it is limited length, or maybe you need to write special marker bytes for this scenario)
  2. their server code doesn't implement the specification correctly (biggest causes are: buffer issues, or: assuming a logical frame arrives in a single network packet)

Actually, I find it interesting that it is doing anything yet, as there is no obvious "frame" there; TCP is a stream, so you ususally need frames to divide logical messages. This usually means one of:

  • a length prefix, with or without other header data
  • a cr/lf/crlf terminator (or other terminator), usually for text-based protocols
  • closing the socket (the ultimate terminator)

You do none of those, so in any server I write, that would be an incomplete message until something else happens. It sounds text-based; I'd try adding a cr/lf/crlf

Upvotes: 1

Related Questions