繁体   English   中英

C# Winform 使用 IP 连接到设备

[英]C# Winform to Connect to Device Using IP

我需要创建一个应用程序,允许用户通过 wifi 连接到设备(一块将发送参数/命令的硬件)(wifi 是最终目标,但我目前正在解决任何连接),然后发送命令到所述设备。 我知道一些 C# 和一些套接字/IP 的东西,但不知道使用 C# 的套接字/IP。 程序的可视化、GUI 方面不是我正在努力的。 我似乎无法启动并运行套接字并建立任何真正的连接。 我不断收到“提供了无效参数”异常。

有关此特定问题的任何提示或有关 C# 网络/套接字/等的帮助。 受欢迎的。

我通过以下方式声明一个新的套接字:

Socket sck;
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

当它尝试处理“sck = new Socket(...);”时抛出异常

有问题的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace InternetConnect
{
    public partial class Form1 : Form
    {
        // Global Variables
        int portNumber = 0;
        string ipAddress = "";
        TcpClient client;

        Socket sck;
        EndPoint epLocal, epRemote;

        // Needs to be defined at some point
        // These are just holding a place for now
        string extraIP = "127.0.0.1";
        string extraPort = "135";

        public Form1()
        {
            InitializeComponent();

            try
            {
                sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void connectButton_Click(object sender, EventArgs e)
        {
            try
            {
                epLocal = new IPEndPoint(IPAddress.Parse(ipAddressTextBox.Text), Convert.ToInt32(portNumberTextBox.Text));
                MessageBox.Show("Before Bind");
                sck.Bind(epLocal);

                MessageBox.Show("After Bind");

                epRemote = new IPEndPoint(IPAddress.Parse(extraIP), Convert.ToInt32(extraPort));
                sck.Connect(epRemote);

                MessageBox.Show("After Connect");

                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

                connectButton.Text = "Connected";
                connectButton.Enabled = false;
                sendButton.Enabled = true;
                outgoingTextBox.Focus();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            ipAddress = ipAddressTextBox.Text;
            // To make sure there are no letters in the IP Address
            int errorCounter = Regex.Matches(ipAddress, @"[a-zA-Z]").Count;
            if (errorCounter == 0)
            {
                if (ipAddress != "")
                {
                    // To make sure the port number is entered without letters
                    if (int.TryParse(portNumberTextBox.Text, out portNumber))
                    {
                        WriteToStatusBar("IP Address and Port Number Valid");
                    }
                    else
                    {
                        MessageBox.Show("Please enter a valid Port Number.");
                    }
                }
                else
                {
                    MessageBox.Show("Please enter a valid IP Address.");
                }
            }
            else
            {
                MessageBox.Show("Please enter a valid IP Address.");
            }
            #endregion

            try
            {
                client = new TcpClient();
                WriteToStatusBar("Connecting...");
                client.Connect(ipAddress, portNumber);
                WriteToStatusBar("Connected");
                outgoingTextBox.Text = "Enter message to be sent to the device...";

                client.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
}

根据 OP 的请求,提供一些有关使用 TcpClient 甚至 TcpListener 的信息,以防您还需要创建服务器。 以下链接将帮助您开始使用 TcpClient: https ://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx ? f = 255 & MSPPError =- 2147217396

或代码项目中的这个涵盖客户端和服务器: http : //www.codeproject.com/Articles/1415/Introduction-to-TCP-client-server-in-C

在该代码(第一个链接)中,您会发现以下语句:stream.Write(data, 0, data.Length);
您想多次写入套接字,然后假设您将相同的数据写入两次,您可以简单地执行以下操作:

stream.Write(data, 0, data.Length);
stream.Write(data, 0, data.Length);

在接收方,您必须意识到,因为 TCP 正在流式传输,您可能会在一次接收中收到 2 个发送“消息”或分散在多个接收中。

在代码中你会发现:

stream.Close();         
client.Close();   

结束通信并关闭套接字,在关闭后发送不再可能。

使用套接字以及 tcpclient 和 tcplistener(因为它们基于套接字)是我认为有点高级的材料。 没有真正了解什么是流,什么是 IP 地址,什么是 TCP,UDP,如何使用套接字,对线程有一些基本的了解。 很容易迷路。 我是一个专业的程序员,我看了很多资料后没有接触这个材料。

最好的办法是根据互联网和书籍上的示例进行更多调查。 并使用这种媒介提出非常具体的专门问题。 复杂的问题往往会在没有正确答案的情况下被关闭,这当然会导致沮丧。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM