Make it Better
Unity Tcp通信
2016-10-7 StanWind

SingleSocket


using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
/*
* SocketClient
* Instance
* By StanWind
*/
public class SocketSingle {
private SocketSingle()
{

}

private static SocketSingle instance;

public static SocketSingle Instance
{
get
{
if (instance == null)
{
instance = new SocketSingle();
}
return instance;
}
}

//把收到的ByteBuffer回传给主线程 之后可以做一个携程处理
public delegate void MyCallback(ByteBuffer bb);

#region 客户端部分

//客户端的socket
private Socket clientSocket;
//客户端消息的委托对象
private MyCallback clientCallback;
//客户端的缓存
private byte[] clientBuffer;

/// <summary>
/// 客户端连接服务器的方法
/// </summary>
/// <param name="userCallback">User callback.</param>
/// <param name="ip">Ip.</param>
/// <param name="port">Port.</param>
public void ClientConnect(MyCallback userCallback,
string ip, int port)
{
//实例化客户端套接字
clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
//实例化客户端缓存数组
clientBuffer = new byte[1024];
//赋值委托对象
clientCallback = userCallback;
//根据ip地址和端口连接到服务器
clientSocket.Connect(IPAddress.Parse(ip), port);
//客户端进行异步接收
clientSocket.BeginReceive(clientBuffer,
0, clientBuffer.Length, SocketFlags.None,
ClientReceive, clientSocket);
}

/// <summary>
/// 客户端接收消息的回调方法
/// </summary>
/// <param name="ar">Ar.</param>
void ClientReceive(System.IAsyncResult ar)
{
//接收结果
Socket workingSocket = ar.AsyncState as Socket;
//接收结束
int count = workingSocket.EndReceive(ar);
//将缓存中接收到的消息转成ByteBuffer
string msgResult = NumberUtils.byteToHexString(clientBuffer);
//System.Console.WriteLine(msgResult);
ByteBuffer bb = new ByteBuffer(clientBuffer);
//回调主线程
Debug.Log("aaaa");
clientCallback(bb);
clientBuffer = new byte[1024];
//尾部递归
workingSocket.BeginReceive(clientBuffer, 0, clientBuffer.Length,
SocketFlags.None, ClientReceive, workingSocket);
}

/// <summary>
/// 客户端发送消息
/// </summary>
/// <param name="msg">Message.</param>
public void ClientSend(byte[] msg)
{
//客户端发送
clientSocket.BeginSend(msg, 0, msg.Length,
SocketFlags.None,
Send,
clientSocket);
}

private void Send(System.IAsyncResult ar)
{
Socket workingSocket = ar.AsyncState as Socket;
//结束接收
int count = workingSocket.EndSend(ar);
//clientCallback("已发送" + count + "byte");
//System.Console.WriteLine("已发送" + count + "byte");
}

#endregion
}



主线程Handler


using UnityEngine;
using System.Collections;
using UnityEngine.UI;

/*
* 控制消息收发
* 活跃在主线程
* By StanWind
*/
public class ClientHandler : MonoBehaviour{

void Start(){
Application.runInBackground = true;
//匿名委托函数
// SocketSingle.Instance.ClientConnect((ByteBuffer bb) =>{
// Debug.Log("I got you");
// Debug.Log(NumberUtils.byteToHexString(bb.ToArray()));
// }
// , "127.0.0.1", 8001);

//非匿名委托
SocketSingle.Instance.ClientConnect(Handler
, "127.0.0.1", 8001);
}

void Handler(ByteBuffer bb){
Debug.Log ("Rec in Main Thread");
Debug.Log(NumberUtils.byteToHexString(bb.ToArray()));

}

public void OnClick(){
SocketSingle.Instance.ClientSend(NumberUtils.hexStringToBytes("4D 5A 00 00 00 00 00 00 00 02 35 32 00 00 00 01"));
}

void Update(){

}
}








发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容