Click here to Skip to main content
15,884,836 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an ethernet device (PIC microcontroller) that is programmed to receive simple commands via ethernet. I have it working perfectly using the Winsock2005DLL.Winsock control. I'm trying without success to convert the code to use the System.Sockets.Socket class instead. Where am I missing ?

With the following 'Winsock' code, a connection is made and the device responds correctly to the hex commands:
C#
// make the connection
Winsock2005DLL.Winsock ws = new Winsock2005DLL.Winsock();
ws.RemotePort = 8888;
ws.RemoteServer = "10.0.0.10";
ws.Connect();

//prepare the data for sending
string s = "";
char cmd = (char)'\x00C0';
char[] bData = new char[] { (char)'\x00FE', (char)'\x00C0', (char)'\x00FF' };
foreach (char c in bData)
       s += c.ToString();

// send the data
ws.Send(s);


This 'Socket' code however, creates the connection successfully, but the device DOESN'T respond to the hex data that is sent.
C#
// make the connection
System.Net.EndPoint ep = new IPEndPoint(IPAddress.Parse("10.0.0.10"), 8888);
System.Net.Sockets.Socket sckt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sckt.Connect(ep);

// prepare the data for sending
string s = "";
char cmd = (char)'\x00C0';
char[] bData = new char[] { (char)'\x00FE', (char)'\x00C0', (char)'\x00FF' };
foreach (char c in bData)
       s += c.ToString();
byte[] bitData = System.Text.Encoding.ASCII.GetBytes(bData);

// send the data
sckt.Send(bitData);


Any help would be greatly appreciated.
Posted

1 solution

If I'm not completely wrong here I think the problem is encoding.
Winsock uses ANSI as a default which in turn I believe on Windows is 1252 and you are converting your string to ASCII which is a different encoding.

Try changing your code to rather use the following:

C#
Encoding ansiEncoding = Encoding.GetEncoding(1252);

string s = "";
char cmd = (char)'\x00C0';
char[] bData = new char[] { (char)'\x00FE', (char)'\x00C0', (char)'\x00FF' };
foreach (char c in bData)
       s += c.ToString();

byte[] bitData = ansiEncoding.GetBytes(bData);


Hope this works for you, but let me know
 
Share this answer
 
Comments
TheRedEye 18-Sep-12 6:21am    
Thanks andrevdcolff, you're a hero. Works great.
andrevdcolff 18-Sep-12 6:38am    
hehe no problem, its normally the small things that get you bogged down.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900