private static extern int AddIPAddress(IPADDR Address, IPMASK IpMask, uint IfIndex, out ulong NTEContext, out ulong NTEInstance);
private extern static int AddIPAddress(IPADDR Address, IPMASK IpMask, uint IfIndex, out ulong NTEContext, out ulong NTEInstance);
private void ConnectButton_Click(object sender, EventArgs e) { string clientId = DateTime.Now.ToString(); CliendID.Text = clientId; if (IPADDR.Text.Length == 0) { MessageBox.Show("请输入服务器地址!"); return; } if (PORT.Text.Length == 0) { MessageBox.Show("端口号为空,请输入端口号!"); return; } if (!IPCheck(IPADDR.Text)) { if (!domainnameToip(IPADDR.Text)) { MessageBox.Show("IP或域名格式不正确!"); IPADDR.Text = string.Empty; IPADDR.Focus(); return; } } int port = Convert.ToInt32(PORT.Text); if (port > 65535) { MessageBox.Show("端口号超过65535,请输入正确端口号!"); PORT.Text = string.Empty; PORT.Focus(); return; } string username = "******"; string password = "******"; string[] topics = new string[1]; if (Sub.Text.Length != 0) { topics[0] = Sub.Text; } else { topics[0] = "+"; Sub.Text = "+"; } byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE }; try { if (string.Compare(ConnectButton.Text, "connect") == 0) { //单向SSL通信 client = new MqttClient(IPADDR.Text, port, false, null, null, MqttSslProtocols.None); //消息接受 client.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(messageReceive); //连接Broker client.ConnectionClosed += new MqttClient.ConnectionClosedEventHandler(ConnectState); client.Connect(clientId, username, password); client.Subscribe(topics, qosLevels); ConnectFlag = true; Sub.Enabled = false; PORT.Enabled = false; IPADDR.Enabled = false; DeviceID.Enabled = true; FilePath.Enabled = true; CliendID.Enabled = false; PubTopic.Enabled = true; UpgradeButton.Enabled = true; FileButton.Enabled = true; FilePushButton.Enabled = true; ConnectButton.Text = "disconnect"; return; } else { client.Disconnect(); Sub.Enabled = true; ConnectFlag = false; PORT.Enabled = true; IPADDR.Enabled = true; DeviceID.Enabled = false; CliendID.Enabled = true; FilePath.Enabled = false; FileButton.Enabled = false; FilePushButton.Enabled = false; PubTopic.Enabled = false; UpgradeButton.Enabled = false; ConnectButton.Text = "connect"; return; } } catch (System.Exception) { MessageBox.Show("MQTT服务器连接失败,请重新连接!"); PORT.Enabled = true; IPADDR.Enabled = true; CliendID.Enabled = true; FilePath.Enabled = false; FileButton.Enabled = false; FilePushButton.Enabled = false; ConnectButton.Text = "connect"; return; } }