简体   繁体   中英

C# Winform to Connect to Device Using IP

I need to create an application that allows the user to connect to a device (a piece of hardware that will be sent arguments/commands) via wifi (wifi is end goal but I am settling at the moment for any connection) and then send commands to said device. I know some C# and some sockets/IP stuff, but not sockets/IP using C#. The visual, GUI side of the program is not what I am struggling with. I cannot seem to get the socket up and running and make any real connection. I keep getting the "An Invalid Argument was Supplied" exception.

Any tips on this particular issue or help with C# networking/sockets/etc. are welcome.

I declare a new socket by:

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

The exception is thrown when it tries to process the "sck = new Socket(...);"

Code in Question:

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);
            }
        }
}

As per request of the OP some information about using TcpClient and even TcpListener in case you need to create a server as well. Following link will help you get started with using TcpClient : https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

or this one in code project covers both client and server: http://www.codeproject.com/Articles/1415/Introduction-to-TCP-client-server-in-C

in that code (the first link) you'll find following statement : stream.Write(data, 0, data.Length);
You want to write multiple times to the socket then suppose you write the same data twice you can do simply :

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

At the receiver, you have to realise that because TCP is streaming, you might receive to 2 send 'messages' in one receive or scattered over multiple receives.

Further in the code you will find :

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

Which ends the communication and closes the socket, sending after doing the close is not possible anymore.

Using sockets, but also tcpclient and tcplistener (because they are based on sockets), is something that I consider a bit advanced material. Without really understanding what streaming is, what IP addressing is, what TCP, UDP is, how to use sockets , some basic understanding of threads. It is easy to get lost. I am a professional programmer, and I did not touch this material after I read quite a lot of information about it.

The best thing to do is to do more investigation, based on examples on the internet & books. And ask very specific dedicated questions using this medium. Elaborate questions have a tendency to get closed without proper answer which will lead to frustration of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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