You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
118 lines
3.6 KiB
118 lines
3.6 KiB
using System.Collections; |
|
using System.Collections.Generic; |
|
using UnityEngine; |
|
using QFramework; |
|
|
|
namespace TCPClientTools |
|
{ |
|
//统筹管理TCP的命令池以及相关链接信息 |
|
public class TCPEventModel : DataEventModel, ICanSendCommand,ICanRegisterEvent |
|
{ |
|
private TCPLinkState tcpState = TCPLinkState.NoIp; |
|
private string tcpAddress = ""; |
|
private int tcpPort = 0; |
|
public string myAddress = ""; |
|
protected override void OnInit() |
|
{ |
|
myAddress = this.GetUtility<TCPUtility>().GetIP(); |
|
this.RegisterEvent<onLinkException>(e=> { |
|
setTCPState(TCPLinkState.LinkTimeOut); |
|
this.GetUtility<TCPUtility>().CloseTCPClient(); |
|
}); |
|
//注册重写发送事件 |
|
this.RegisterEvent<RequestMsgEvent>(e => { |
|
if (this.GetUtility<TCPUtility>().isOpenTCP) |
|
{ |
|
this.GetUtility<TCPUtility>().sendData(e.req.toJson()); |
|
} |
|
else |
|
{ |
|
Debug.LogWarning("请先开启TCP链接"); |
|
} |
|
}); |
|
} |
|
public void setTCPState(TCPLinkState state) { |
|
this.tcpState = state; |
|
this.SendEvent(new TCPStateChangedEvent(state)); |
|
} |
|
public TCPLinkState getState() { |
|
return this.tcpState; |
|
} |
|
/// <summary> |
|
/// 设置对应IP,设置完毕后,自动进入链接状态(此时需要用户手动监听是否要进行链接服务器) |
|
/// </summary> |
|
/// <param name="ip">ip地址</param> |
|
/// <param name="port">端口号</param> |
|
public void setIP(string ip,int port) { |
|
this.tcpAddress = ip; |
|
this.tcpPort = port; |
|
//此处可以加ip校验 |
|
Debug.LogWarning("此处未进行ip以及端口号校验,日后有需求可以增加"); |
|
setTCPState(TCPLinkState.Linking); |
|
} |
|
/// <summary> |
|
/// 与服务端建立链接 |
|
/// </summary> |
|
public void linkServer() { |
|
if (tcpState == TCPLinkState.Linking) |
|
{ |
|
if (!this.GetUtility<TCPUtility>().isOpenTCP) { |
|
|
|
bool isSuccess = this.GetUtility<TCPUtility>().StartTCPClient(tcpAddress, tcpPort); |
|
if (isSuccess) { |
|
setTCPState(TCPLinkState.LinkSucess); |
|
} |
|
else |
|
{ |
|
setTCPState(TCPLinkState.LinkFaild); |
|
} |
|
} |
|
} |
|
} |
|
/// <summary> |
|
/// 与服务端断开链接 |
|
/// </summary> |
|
public void closeServer() |
|
{ |
|
if (tcpState == TCPLinkState.LinkSucess) |
|
{ |
|
if (this.GetUtility<TCPUtility>().isOpenTCP) |
|
{ |
|
|
|
this.GetUtility<TCPUtility>().CloseTCPClient(); |
|
setTCPState(TCPLinkState.NoIp); |
|
} |
|
} |
|
} |
|
} |
|
|
|
#region enum |
|
public enum TCPLinkState |
|
{ |
|
NoIp = 0, |
|
Linking = 1, |
|
LinkFaild = 2, |
|
LinkSucess = 3, |
|
LinkTimeOut = 4 |
|
} |
|
#endregion |
|
|
|
#region event |
|
public struct TCPStateChangedEvent |
|
{ |
|
public TCPLinkState state; |
|
public TCPStateChangedEvent(TCPLinkState state_) |
|
{ |
|
state = state_; |
|
} |
|
} |
|
public struct onLinkException |
|
{ |
|
public string exceptionMsg; |
|
public onLinkException(string exceptionMsg_) |
|
{ |
|
exceptionMsg = exceptionMsg_; |
|
} |
|
} |
|
#endregion |
|
} |