概述
最近,这个问题严重地杀了我。我正在尝试通过服务器和客户端通过网络建立连接。在显示代码之前,我想说一下我已经搜索了多个线程来解决此问题,但是这让我很疯狂。
错误:连接尝试失败是因为一段时间后被连接方未正确响应,或者是由于连接的主机未能响应而导致建立连接失败。
从这里开始的事情是我尝试过的事情的列表:
端口转发
-使用本地IP和LAN IP(即127.0.0.1、192.168.1.4、10.0.0.150),这些IP将起作用并将我连接到服务器,而我的外部IP无法使用。
-经过检查的防火墙
-尝试使用其他端口,以防ISP阻止特定端口(25567、28567等)
现在输入我的代码...
客户端Unity3D:
public string host = "Insert IP Here";
public int port = 25567;
public TcpClient socket = new TcpClient();
public void ConnectToServer()
{
while (true)
{
try
{
socket.ReceiveTimeout = 100;
socket.SendTimeout = 100;
socket.Connect(new IPEndPoint(IPAddress.Parse(host), port));
stream = socket.GetStream();
writer = new StreamWriter(stream);
reader = new StreamReader(stream);
MasterCommunication MC = GameObject.Find("Main").GetComponent<MasterCommunication>();
MC.setCommunicationPrams(socket, stream, reader, writer, true);
socketReady = true;
break;
}
catch (Exception e)
{
Debug.Log("Connection timed out.");
Debug.Log(e.Message);
break;
}
}
}
服务器(Visual Studio):
public static int port = 63292;
private static TcpListener server;
static void Main(string[] args) // Main Method
{
#region Initialization
Console.WriteLine("...Server Initializing");
clients = new List<ServerClient>();
disconnectList = new List<ServerClient>();
try
{
IPEndPoint IPEP = new IPEndPoint(IPAddress.Any, port);
Console.WriteLine("...IPEP set to " + IPEP.AddressFamily);
Console.WriteLine("...Port Set to " + port);
server = new TcpListener(IPEP);
server.Start();
StartListening();
Thread dataListener = new Thread(ListenForData);
dataListener.Start();
if (Directory.Exists(Directory.GetCurrentDirectory() + "/Database"))
{
Console.WriteLine("...Database Found");
}
else
{
Directory.CreateDirectory(Directory.GetCurrentDirectory() + "/Database");
Console.WriteLine("...Database Created");
}
Database.VerifyDatabase(Directory.GetCurrentDirectory() + "/Database");
Console.WriteLine("...Server has successfully started.");
}
catch (Exception e)
{
Console.WriteLine("Socket error: " + e.Message);
}
#endregion
}
服务器(下半部分)
private static void StartListening() => server.BeginAcceptTcpClient(AcceptTcpClient, server);
private static void AcceptTcpClient(IAsyncResult ar)
{
try
{
Console.WriteLine("-New Connection");
TcpListener listener = (TcpListener)ar.AsyncState;
clients.Add(new ServerClient(listener.EndAcceptTcpClient(ar)));
StreamWriter writer = new StreamWriter(clients.Last<ServerClient>().tcp.GetStream());
writer.WriteLine(Encryption.Encrypt("Connected~Connected"));
writer.Flush();
StartListening();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
StartListening();
}
}
半T ^ T