124 lines
3.8 KiB
C#
Raw Normal View History

using Assets.Scenes.Ride.Scripts.Model;
using Assets.Scripts;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Assets.Scenes.Ride.Scripts.Network
{
public class TcpService1 : IService
{
private bool isExit = false;
private PfTcpClient _tcpClient;
private IPEndPoint iPEndPoint;
//private Action<List<ReceiveMsgModel>> _action;
public void Start(Action<List<ReceiveMsgModel>> action)
{
if (_tcpClient == null)
{
//if (!IPAddress.TryParse(ConfigHelper.ServerIpAdress, out var ipString))
//{
// throw new ArgumentException("IP地址不正确");
//}
//服务端端口
iPEndPoint = ConfigHelper.TcpAddress;
_tcpClient = new PfTcpClient(iPEndPoint.Address.ToString(), 11001, action);
_tcpClient.OptionNoDelay = true;
//_action = action;
_tcpClient.ConnectAsync();
}
}
public void Send(byte[] dgram, int bytes)
{
if (_tcpClient == null) return;
if (_tcpClient.IsConnected == false) return;
//_tcpClient.WriteLine(System.Text.Encoding.ASCII.GetString(dgram));
var txt = System.Text.Encoding.ASCII.GetString(dgram);
//Debug.WriteLine("发送:"+txt);
_tcpClient.Send(txt);
}
public void Close()
{
isExit = true;
_tcpClient.DisconnectAndStop();
_tcpClient = null;
}
class PfTcpClient : NetCoreServer.TcpClient
{
private bool _stop;
Action<List<ReceiveMsgModel>> _action;
public PfTcpClient(string address, int port, Action<List<ReceiveMsgModel>> action) : base(address, port)
{
_action = action;
}
public void DisconnectAndStop()
{
_stop = true;
DisconnectAsync();
while (IsConnected)
{
Thread.Yield();
}
}
protected override void OnConnected()
{
base.OnConnected();
}
protected override void OnDisconnected()
{
//base.OnDisconnected();
Debug.WriteLine("tcp断线3秒后重连");
Thread.Sleep(3000);
if (!_stop)
{
ConnectAsync();
}
}
protected override void OnReceived(byte[] buffer, long offset, long size)
{
//base.OnReceived(buffer, offset, size);
var returnData = Encoding.UTF8.GetString(buffer, (int)offset, (int)size);
//Debug.WriteLine("收到:" + returnData+"\r\n");
//System.IO.File.AppendAllText(System.Environment.CurrentDirectory + "接收到的数据.txt", returnData.Trim().Replace("\0", "")+"\r\n", Encoding.UTF8);
var list = new List<ReceiveMsgModel>();
var itemList = returnData.Split('|');
foreach (var item in itemList)
{
var info = ReceiveMsgModel.Parse(item);
if (info != null)
{
list.Add(info);
}
}
_action(list);
}
protected override void OnError(SocketError error)
{
//base.OnError(error);
Debug.WriteLine(error);
}
}
}
}