几天前我问了一个类似的问题。那时,我正在尝试使用套接字。目前,我正在使用 TCPClient 为我做脏套接字工作。我正在使用 Windows 7 和 Visual Studios 2013 Professional。
原始和当前项目大纲:
我需要创建一个应用程序(使用 C# 的 WinForms),允许用户通过 wifi 连接到设备(将发送参数/命令的硬件)(wifi 是最终目标,但我目前正在解决任何连接) 然后向所述设备发送消息。我知道一些 C# 和一些套接字/IP 的东西,但不知道使用 C# 的套接字/IP。程序的视觉、GUI 方面并不是我所苦苦挣扎的。我似乎无法启动并运行 TCPClient 并建立任何真正的连接。我不断收到“提供了无效参数”异常。
有关此特定问题的任何提示或 C# 网络/TCPClient/等方面的帮助。受欢迎的。
我尝试通过以下每种方式创建一个新的 TcpClient ,但均未成功:
TcpClient tcpClient = new TcpClient();
TcpClient tcpClient = new TcpClient(family); // family is a created AddressFamily
TcpClient tcpClient = new TcpClient(clientIPAddress, clientPortNumber);
TcpClient tcpClient = new TcpClient(remoteEP); // remoteEP is a remote end point created by me
TcpClient tcpClient = new TcpClient(localEP); // localEP is a local end point
其中每一个都是 TCPClient 类中的构造函数之一。这些中的每一个都给了我以下例外: 提供了无效的参数
堆栈跟踪:
在 System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)\r\n 在 System.Net.Sockets.TcpClient.initialize()\r\n 在 System.Net.Sockets.TcpClient。 .ctor(AddressFamily family)\r\n at System.Net.Sockets.TcpClient..ctor()\r\n at ConnectLite.ConnectLite.MakeConnection() in h:\Howard\Projects\ConnectLite\ConnectLite\Form1.cs :第 120 行
我确实拥有所有必要的导入和使用。
当我尝试在另一台计算机上运行应用程序时,这个问题变得很奇怪。在不同的计算机上,无论是从调试文件中运行没有 Visual Studios 的应用程序,还是使用 Visual Studios 2013 在另一台计算机上运行它,应用程序都比异常更进一步,并且永远不会引发异常。
我只是想使用 TCPClient 来做一些简单的消息发送。然而,TCPClient 阻止了我这样做。
当我一直在使用套接字时,它在创建新套接字时抛出了同样的异常。
Socket clientSocket =
new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
你们中有人对此事有任何见解吗?
为简化起见,我将相关代码段放入控制台应用程序中,以便于阅读。
有问题的简单代码块:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleTestConnectLite
{
class Program
{
static void Main(string[] args)
{
try
{
TcpClient tcpClient = new TcpClient();
}
catch (SocketException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Error: " + e.StackTrace);
Console.WriteLine(e.Message + ". Error Code: " + e.ErrorCode.ToString());
}
}
}
}
控制台输出:
An invalid argument was supplied
Error: at System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, Socket
Type socketType, ProtocolType protocolType)
at System.Net.Sockets.TcpClient.initialize()
at System.Net.Sockets.TcpClient..ctor(AddressFamily family)
at System.Net.Sockets.TcpClient..ctor()
at ConsoleTestConnectLite.Program.Main(String[] args) in h:\Howard\Projects\ConsoleTestConnectLite\ConsoleTestConnectLite\Program.cs:line 17
An invalid argument was supplied. Error Code: 10022
Press any key to continue . . .