Tcp内部网连接C#出现问题



我在连接在同一个wifi网络上的两个设备(PC和手机(之间建立TCP连接时遇到问题,代码似乎很好,但客户端(在我的情况下,是手机(一直在尝试连接,服务器(PC(在等待连接,最终什么都没发生。我试着在电脑上配置我的防火墙,但它仍然不起作用。我希望这些应用程序可以在其他电脑上运行,而无需配置太多,而且方式非常简单,因为它是一种在大学里公开的工具。

我还允许他连接到互联网的移动应用程序

在这里我留下电脑的代码:

class TcpServerCode
{
IPEndPoint ipEnd;
Socket sock;
public TcpServerCode(int port)
{
ipEnd = new IPEndPoint(IPAddress.Any, port);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
public static string curMsg = "Stopped";
public void StartServer()
{
try
{
curMsg = "Starting...";
sock.Listen(100);
curMsg = "Running and waiting to receive file.";
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024];
int receivedBytesLen = clientSock.Receive(clientData);
curMsg = "Receiving data...";
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string getStr = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
Form1.Singletone.ConsoleLog(getStr);
clientSock.Close();
}
catch (Exception ex)
{
curMsg = "Error.";
}
}
}

这里的手机:

class TcpClientCode
{
public static string curMsg = "Idle";
public static void SendComand(string comand)
{
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
byte[] fileNameByte = Encoding.ASCII.GetBytes(comand);
byte[] clientData = new byte[4 + fileNameByte.Length];
curMsg = "Connection to server ...";
clientSock.Connect(ipEnd);
curMsg = "Command sending...";
clientSock.Send(clientData);
curMsg = "Disconnecting...";
clientSock.Close();
curMsg = "transferred.";
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

对于那些想知道的人来说,我通过SushiHangover解决了这个问题,问题是我必须让我的客户端连接到服务器的IPv4,因为它位于intranet系统中。

获取本地Ip地址:

public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}

检查您是否已连接:

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

从获取本地IP地址获取的信息

最新更新