第一部分简单示例:连接服务器Ip 端口,发送请求,接收数据同理。
public static void SocketConnect(string serverIP, int serverPort)
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
try
{
clientSocket.Connect(ipe);
Debug.Log(" Connect Success IP: " + serverIP + " Port : " + serverPort.ToString());
}
catch (Exception e)
{
Debug.LogError(e.ToString());
}
} //Unity3D教程手册:www.unitymanual.com
//发送数据
public static void Send(byte[] bytes)
{
if (clientSocket == null)
return;
if (!clientSocket.Connected)
return;
if (clientSocket.Poll(0, SelectMode.SelectWrite))
{
try
{
clientSocket.Send(bytes);
}
catch (Exception e)
{
Debug.LogError(e.ToString());
}
}
}
第二部分请求数据示例:
public void _MSG_ACCOUNT(string name, string pwd)
{
ACCOUNT account = new ACCOUNT();
datas = new byte[account.length];
byte[] bytesLength = BitConverter.GetBytes((System.Int16)account.length);
int length = 0;
bytesLength.CopyTo(datas, length);
length += 2;
byte[] bytesID = BitConverter.GetBytes((System.Int16)account.ID);
bytesID.CopyTo(datas, length);
length += 2;
byte[] bytesName = Encoding.Default.GetBytes(name);
bytesName.CopyTo(datas, length);
第三部分接收数据示例:
void _MSG_CONNECT(byte[] datas)
{
connect = new CONNECT();
int length = 4;
connect.idAccount = BitConverter.ToUInt32(datas, length);
Debug.LogError("账号ID " + connect.idAccount);
//Unity3D教程手册:www.unitymanual.com
length += System.Runtime.InteropServices.Marshal.SizeOf(connect.idAccount);
connect.dwData = BitConverter.ToUInt32(datas, length);
Debug.LogError("认证ID " + connect.dwData);
length += System.Runtime.InteropServices.Marshal.SizeOf(connect.dwData);
connect.nServerIndex = BitConverter.ToUInt32(datas, length);
Debug.LogError("游戏逻辑服务器索引 " + connect.nServerIndex);