【发布时间】:2020-03-14 03:14:49
【问题描述】:
我无法在同一个 wifi 网络(PC 和手机)上连接的两台设备之间建立 TCP 连接,代码似乎没问题,但客户端(在我的情况下是手机)一直在尝试连接和服务器( pc ),等待连接,最后什么也没有发生。我试图在 PC 上配置我的防火墙,但它仍然不起作用。我希望这些应用程序可以在其他 PC 上运行而无需进行太多配置,而且方式非常简单,因为它是在大学中公开的工具。
我还授予他将互联网连接到移动应用程序的权限
这里我留下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);
}
}
}
【问题讨论】:
-
您在设备上使用“localhost”,因此尝试连接到设备本身,而不是您的 PC,请使用 PC 的 IP 地址
-
我已经试过了,但在尝试连接电脑时仍然崩溃
-
是的,是的,你知道我怎样才能得到机器的正确 ip 吗?
标签: c# windows forms xamarin server