【问题标题】:Why is this PortName deemed nonexistent?为什么这个 PortName 被认为不存在?
【发布时间】:2014-12-16 00:12:36
【问题描述】:

我正在尝试重构/更新一些旧的串行通信代码。我有这个:

private SerialPort cereal;
private String receivedData;

private FileXferLegacy()
{
    cereal = new SerialPort("COM1", 9600);
    cereal.PortName = "7727";
    cereal.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
    // Is this just as well, as the elided part is grayed out above?: cereal.DataReceived += port_DataReceived;
}

...但是当我尝试连接并发送 ping 时收到错误消息“端口 '7727:' 不存在”:

public void SendDataContentsAsXML(string destinationPath, string XMLData)
{
    byte[] stuff;
    ExceptionLoggingService.Instance.WriteLog("Reached FileXferLegacy.SendDataContentsAsXML"); // <= This is written to the log file
    cereal.Open();
    stuff = System.Text.UTF8Encoding.UTF8.GetBytes("PING" + "\n");
    cereal.Write(stuff, 0, stuff.Length);
    stuff = System.Text.UTF8Encoding.UTF8.GetBytes(XMLData + "\n");
    cereal.Write(stuff, 0, stuff.Length);
}

7727 与旧版应用中成功使用的端口相同。

我确实看到附加了一个冒号,并想知道这是否是问题所在 - 为什么它看到“7727:”而不是普通的旧“7727”,我如何才能消除附加的概念冒号,如果这确实是一个问题?

【问题讨论】:

    标签: c# serial-port compact-framework windows-ce port-number


    【解决方案1】:

    因为PortName 指的是串口名称,而不是端口号。在您的代码中,您正在创建 SerialPort 对象

    cereal = new SerialPort("COM1", 9600);
    

    所以COM1 已经分配给PortName。您的下一个语句只是不必要且错误地覆盖它。

    【讨论】:

    • 那么如何设置端口(不是串口的名称,而是发送数据的端口)?旧版应用程序使用 7727,因此必须有办法做到这一点,但我在 SerialPort 类上看不到可能的属性。
    • 串口没有端口号。串行端口用于单个端到端连接,因此没有端口号的概念;这是用于 TCP/UDP 连接的。
    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多