UDP客户端网络接连方式
创建Socket
private void GetSeverIp()
{
try
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_endPoint = new IPEndPoint(IPAddress.Any, _udpPort);
//端口复用
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_socket.Bind(_endPoint);
_data = new byte[1024];
StartCoroutine("IeReceive");
}
catch (Exception e)
接收服务端的数据
WaitForEndOfFrame _waittime = new WaitForEndOfFrame();
IEnumerator IeReceive()
{
while (!_isStop)
{
if (_socket.Available > 0)
{
int recv = _socket.ReceiveFrom(_data, 1024, SocketFlags.None, ref _endPoint);
if (recv <= 0)
{
continue;
}
string msg = Encoding.ASCII.GetString(_data, 0, recv);
_receiveCallback?.Invoke(msg);
isReceive = true;
}
yield return _waittime;
}
}
关闭Socket
private void OnCloseSocket()
{
StopCoroutine("IeReceive");
_isStop = true;
if (_socket !=null)
{
_socket.Close();
_socket = null;
}
}
切换前后台是对socket 进行关闭和重新创建
private void OnApplicationPause(bool isPause)
{
if (isPause)
{
OnCloseSocket();
}
else
{
GetSeverIp();
}
}