从Winsock移到Net.Sockets.Socket [英] Moving from Winsock to Net.Sockets.Socket

查看:62
本文介绍了从Winsock移到Net.Sockets.Socket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以太网设备(PIC微控制器),该设备被编程为通过以太网接收简单命令.我使用Winsock2005DLL.Winsock控件可以完美地工作.我正在尝试将代码转换为使用System.Sockets.Socket类,但没有成功.我在哪里想念?

使用以下"Winsock"代码,建立连接,并且设备正确响应十六进制命令:

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:

// 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.

// 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.

推荐答案

如果我在这里不是完全错误,我认为问题是编码.
Winsock使用ANSI作为默认值,而我相信Windows上的默认值为1252,并且您正在将字符串转换为另一种编码的ASCII.

尝试更改代码以使用以下代码:

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:

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


这篇关于从Winsock移到Net.Sockets.Socket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆