[英]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.