so I was working on a unity 3D game that had an online multiplayer. I was initially planning to use UNET but instead, I made my own c# socket backend. When everything was set up and ready to go, I tested it on the localhost, with 127.0.01 and everything worked excellently. Then I put my server backend onto google cloud and used a static IP address for the host. I used port 26150. I double-checked that 26150 was not used by any other program or app. I can 100% guarantee that I changed the port number and the IP address on my client end, to match the port number and IP I am using. The IP is the google cloud's static IP, and the port is 26150. When I finally tried to connect, it did not work, and gave me this error, "Connection Failed: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it.
at System.Net.Sockets.SocketAsyncResult.CheckIfThrowDelayedException () [0x00014] in <376e8c39bbab4f1193a569c8dbe4305c>:0 at System.Net.Sockets.Socket.EndConnect (System.IAsyncResult asyncResult) [0x0002c] in <376e8c39bbab4f1193a569c8dbe4305c>:0 at System.Net.Sockets.TcpClient.EndConnect (System.IAsyncResult asyncResult) [0x0000c] in <376e8c39bbab4f1193a569c8dbe4305c>:0 ". I even tried to telnet the server's IP address on 26150 and everything worked fine. I also disabled the firewall on the server end. What is the problem? Any ideas would be really helpful. Here is some of the code on the client end.
public string ip = "35.239.35.123";
public int port = 80;
public int myID = 0;
public TCP tcp;
public UDP udp;
private delegate void PacketHandler(Packet _packet);
private static Dictionary<int, PacketHandler> packetHandlers;
private void Awake()
{
if (clientInstance == null)
{
clientInstance = this;
}
else if (clientInstance != this)
{
Debug.Log("instance already exists");
Destroy(this);
}
}
private void Start()
{
tcp = new TCP();
udp = new UDP();
}
public void ConnectToServer()
{
InitializeClientData();
tcp.Connect();
}
private void InitializeClientData()
{
packetHandlers = new Dictionary<int, PacketHandler>()
{
{(int)ServerPackets.welcome, ClientHandle.Welcome },
{(int)ServerPackets.spawnPlayer, ClientHandle.SpawnPlayer },
{(int)ServerPackets.playerPosition, ClientHandle.PlayerMovement },
{(int)ServerPackets.playerRotation, ClientHandle.PlayerRotation }
};
Debug.Log("Initialized packets");
}
public class TCP
{
public TcpClient socket;
private NetworkStream stream;
private Packet receivedData;
private byte[] receiveBuffer;
public void Connect()
{
Debug.Log("Connecting To Server");
socket = new TcpClient
{
ReceiveBufferSize = dataBufferSize,
SendBufferSize = dataBufferSize,
};
receiveBuffer = new byte[dataBufferSize];
try
{
socket.BeginConnect(clientInstance.ip, clientInstance.port, ConnectCallBack, socket);
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
Debug.Log("Connected");
}
private void ConnectCallBack(IAsyncResult _result)
{
Debug.Log("About to end connect");
try
{
socket.EndConnect(_result);
}
catch (Exception e)
{
Debug.LogError($"Connection Failed: {e}");
}
Debug.Log("Closed the connection request");
if (!socket.Connected)
{
Debug.LogError("Connection Failed!");
return;
}
stream = socket.GetStream();
if (stream == null)
{
Debug.LogError("Network Stream Failed!");
}
receivedData = new Packet();
stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallBack, null);
}
public void SendData(Packet _packet)
{
try
{
if (socket != null)
{
stream.BeginWrite(_packet.ToArray(), 0, _packet.Length(), null, null);
}
}
catch (Exception _ex)
{
Debug.LogError($"Error sending data to server via TCP: {_ex} ");
}
}
private void ReceiveCallBack(IAsyncResult _result)
{
try
{
int _byteLength = stream.EndRead(_result);
if (_byteLength <= 0)
{
//TODO: disconnect
return;
}
byte[] _data = new byte[_byteLength];
Array.Copy(receiveBuffer, _data, _byteLength);
receivedData.Reset(HandleData(_data));
stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallBack, null);
}
catch
{
// TODO: disconnect
}
}
private bool HandleData(byte[] _data)
{
int _packetLength = 0;
receivedData.SetBytes(_data);
if (receivedData.UnreadLength() >= 4)
{
_packetLength = receivedData.ReadInt();
if (_packetLength <= 0)
{
return true;
}
}
while (_packetLength > 0 && _packetLength <= receivedData.UnreadLength())
{
byte[] _packetBytes = receivedData.ReadBytes(_packetLength);
ThreadManager.ExecuteOnMainThread(() =>
{
using (Packet _packet = new Packet(_packetBytes))
{
int _packetId = _packet.ReadInt();
packetHandlers[_packetId](_packet);
}
});
_packetLength = 0;
if (receivedData.UnreadLength() >= 4)
{
_packetLength = receivedData.ReadInt();
if (_packetLength <= 0)
{
return true;
}
}
}
if (_packetLength <= 1)
{
return true;
}
return false;
}
}
public class UDP
{
public UdpClient socket;
public IPEndPoint endPoint;
public UDP()
{
endPoint = new IPEndPoint(IPAddress.Parse(clientInstance.ip), clientInstance.port);
}
public void Connect(int _localPort)
{
socket = new UdpClient(_localPort);
socket.Connect(endPoint);
socket.BeginReceive(ReceiveCallBack, null);
using (Packet _packet = new Packet())
{
SendData(_packet);
}
}
public void SendData(Packet _packet)
{
try
{
_packet.InsertInt(clientInstance.myID);
if (socket != null)
{
socket.BeginSend(_packet.ToArray(), _packet.Length(), null, null);
}
}
catch (Exception _ex)
{
Debug.LogError($"Error sending to server via UDP: {_ex}");
}
}
private void ReceiveCallBack(IAsyncResult _result)
{
try
{
byte[] _data = socket.EndReceive(_result, ref endPoint);
socket.BeginReceive(ReceiveCallBack, null);
if (_data.Length < 4)
{
// TODO: disconnect
return;
}
HandleData(_data);
}
catch (Exception _ex)
{
//TODO: disconnect
}
}
private void HandleData(byte[] _data)
{
using (Packet _packet = new Packet(_data))
{
int _packetLength = _packet.ReadInt();
_data = _packet.ReadBytes(_packetLength);
}
ThreadManager.ExecuteOnMainThread(() =>
{
using (Packet _packet = new Packet(_data))
{
int _packetID = _packet.ReadInt();
packetHandlers[_packetID](_packet);
}
});
}
}
}
Here is some of the code on the server end
public static int MaxPlayers { get; private set; }
public static int Port { get; private set; }
public static Dictionary<int, Client> gameClients = new Dictionary<int, Client>();
public delegate void PacketHandler(int _fromClient, Packet _packet);
public static Dictionary<int, PacketHandler> packetHandlers;
private static TcpListener tcpListener;
private static UdpClient udpListener;
/// <summary>
/// Initializes the Server
/// </summary>
/// <param name="_maxPlayers"></param>
/// <param name="_port"></param>
public static void Start(int _maxPlayers, int _port)
{
MaxPlayers = _maxPlayers;
Port = _port;
Console.WriteLine("Initializing Server..,");
InitializeServerData();
tcpListener = new TcpListener(IPAddress.Any, Port);
tcpListener.Start();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(TCPConnectCallBack), null);
udpListener = new UdpClient(Port);
udpListener.BeginReceive(UDPReceiveCallBack, null);
Console.WriteLine($"Server initialized on {Port}.");
}
private static void TCPConnectCallBack(IAsyncResult _result)
{
TcpClient _client = tcpListener.EndAcceptTcpClient(_result);
tcpListener.BeginAcceptTcpClient(new AsyncCallback(TCPConnectCallBack), null);
Console.WriteLine($"Incoming connection from {_client.Client.RemoteEndPoint}");
for (int i = 1; i <= MaxPlayers; i++)
{
if (gameClients[i].tcp.socket == null)
{
gameClients[i].tcp.Connect(_client);
return;
}
}
}
private static void UDPReceiveCallBack(IAsyncResult _result)
{
try
{
IPEndPoint _clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] _data = udpListener.EndReceive(_result, ref _clientEndPoint);
udpListener.BeginReceive(UDPReceiveCallBack, null);
if (_data.Length < 4)
{
return;
}
using (Packet _packet = new Packet(_data))
{
int _clientID = _packet.ReadInt();
if (_clientID == 0)
{
return;
}
if (gameClients[_clientID].udp.endPoint == null)
{
gameClients[_clientID].udp.Connect(_clientEndPoint);
return;
}
if (gameClients[_clientID].udp.endPoint.ToString() == _clientEndPoint.ToString())
{
gameClients[_clientID].udp.HandleData(_packet);
}
}
}
catch (Exception _ex)
{
Console.WriteLine($"Error sending data via UDP {_ex}");
}
}
public static void SendUDPData(IPEndPoint _clientEndPoint, Packet _packet)
{
try
{
if (_clientEndPoint != null)
{
udpListener.BeginSend(_packet.ToArray(), _packet.Length(), _clientEndPoint, null, null);
}
}
catch (Exception _ex)
{
Console.WriteLine($"Error sending data too {_clientEndPoint} via UDP: {_ex}");
}
}
private static void InitializeServerData()
{
for (int i = 1; i <= MaxPlayers; i++)
{
gameClients.Add(i, new Client(i));
}
packetHandlers = new Dictionary<int, PacketHandler>()
{
{(int)ClientPackets.welcomeReceived, ServerHandle.ConnectedSuccessfully },
{(int)ClientPackets.playerMovement, ServerHandle.PlayerMovement },
{(int)ClientPackets.shootBullet, ServerHandle.BulletPosition }
};
Console.WriteLine("Initialized packets...");
}
}
User contributions licensed under CC BY-SA 3.0