I have a problem with connection handling in TCP Client socket.
This code should connect to localhost at 4444 port and listening for all incoming data from this TCP Server.
I need to write connection handling for this. For example if while attempting to connect server is not responding it should trying to connect again, or if connection is ready and after receiving some data TCP server will close the connection TCP client should try to reconnect again.
Can anyone help me with this problems
Here is what I have in this moment
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
public class TCPClientNew : MonoBehaviour {
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
private byte[] _recieveBuffer = new byte[8142];
private void StartClient()
{
try
{
_clientSocket.Connect(new IPEndPoint(IPAddress.Loopback,4444));
}
catch(SocketException ex)
{
Debug.Log(ex.Message);
// Try to reconnect ?? TODO
}
Debug.Log ("connected");
_clientSocket.BeginReceive(_recieveBuffer,0,_recieveBuffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
}
private void ReceiveCallback(IAsyncResult AR)
{
//Check how much bytes are recieved and call EndRecieve to finalize handshake
int recieved = _clientSocket.EndReceive(AR);
if(recieved <= 0)
return;
//Copy the recieved data into new buffer , to avoid null bytes
byte[] recData = new byte[recieved];
Buffer.BlockCopy(_recieveBuffer,0,recData,0,recieved);
//Processing received data
Debug.Log (System.Text.Encoding.ASCII.GetString(recData));
//Start receiving again
_clientSocket.BeginReceive(_recieveBuffer,0,_recieveBuffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
}
private void SendData(byte[] data)
{
SocketAsyncEventArgs socketAsyncData = new SocketAsyncEventArgs();
socketAsyncData.SetBuffer(data,0,data.Length);
_clientSocket.SendAsync(socketAsyncData);
}
void Start()
{
StartClient ();
}
}