TryCatchNetworkFix

This commit is contained in:
AnloGames 2023-08-17 13:05:43 +03:00
parent ccc6937ac9
commit 62a32ccdce

View file

@ -20,21 +20,28 @@ namespace DangerousD.GameCore.Network
string state;
private void Init(string IpAddress)
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress address = IPAddress.Parse(IpAddress);
int port = 8000;
endPoint = new IPEndPoint(address, port);
}
catch { }
}
private void AcceptSockets()
{
while (true)
{
try
{
Socket clientSocket = socket.Accept();
clientSockets.Add(clientSocket);
Thread receiveThread = new Thread(BeginHostReceive);
receiveThread.Start(clientSocket);
Console.WriteLine("Connected");
}
catch { }
}
}
@ -42,6 +49,8 @@ namespace DangerousD.GameCore.Network
{
Socket clientSocket = clSocket as Socket;
while (clientSocket != null)
{
try
{
byte[] bytesCount = new byte[4];
clientSocket.Receive(bytesCount);
@ -49,8 +58,12 @@ namespace DangerousD.GameCore.Network
StateObject so = new StateObject(clientSocket, Data);
IAsyncResult count = clientSocket.BeginReceive(so.buffer, 0, so.bufferSize, SocketFlags.None, AsyncReceiveCallback, so);
}
catch { }
}
}
public void HostInit(string IpAddress)
{
try
{
Init(IpAddress);
socket.Bind(endPoint);
@ -58,9 +71,12 @@ namespace DangerousD.GameCore.Network
Thread acceptThread = new Thread(AcceptSockets);
acceptThread.Start();
state = "Host";
Console.WriteLine("Start Accept");
}
catch { }
}
public void ClientInit(string IpAddress)
{
try
{
Init(IpAddress);
socket.Connect(endPoint);
@ -69,11 +85,15 @@ namespace DangerousD.GameCore.Network
Thread ReceivingThread = new Thread(ReceiveMsgFromHost);
ReceivingThread.Start();
}
catch { }
}
public void SendMsg(NetworkTask networkTask)
{
byte[] Data = Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(networkTask));
int count = Data.Length;
if (state == "Host")
{
try
{
foreach (Socket socket in clientSockets)
{
@ -81,15 +101,23 @@ namespace DangerousD.GameCore.Network
socket.Send(Data);
}
}
catch { }
}
else
{
try
{
socket.Send(BitConverter.GetBytes(count));
socket.Send(Data);
}
catch { }
}
}
private void ReceiveMsgFromHost()
{
while (true)
{
try
{
byte[] bytesCount = new byte[4];
socket.Receive(bytesCount);
@ -97,9 +125,13 @@ namespace DangerousD.GameCore.Network
StateObject so = new StateObject(socket, Data);
IAsyncResult count = socket.BeginReceive(so.buffer, 0, so.bufferSize, SocketFlags.None, AsyncReceiveCallback, so);
}
catch { }
}
}
private void AsyncReceiveCallback(IAsyncResult ar)
{
try
{
StateObject so = ar.AsyncState as StateObject;
Socket clientSocket = so.workSocket;
@ -115,5 +147,7 @@ namespace DangerousD.GameCore.Network
GetReceivingMessages(JsonConvert.DeserializeObject<NetworkTask>(so.sb.ToString()));
}
}
catch { }
}
}
}