using Core.Utilities;
|
using System;
|
using System.Collections;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Net.Sockets;
|
using System.Runtime.CompilerServices;
|
using UnityEngine;
|
|
|
public struct SocketState
|
{
|
public TcpClient client;
|
public NetworkStream socketStream;
|
|
public SocketState( TcpClient c,NetworkStream ns)
|
{
|
this.client = c;
|
this.socketStream = ns;
|
}
|
}
|
|
public class TestTcpSocket : Singleton<TestTcpSocket>
|
{
|
private static object objlock = new object(); // ÓÃÓÚ¶àÏß³ÌËø¶¨.
|
protected static TestTcpSocket instace = null;
|
protected TcpClient client = null;
|
protected NetworkStream socketStream = null;
|
protected Byte[] byteBuffer = new byte[1024 * 1024];
|
protected int MAX_READ = 1024 * 1024;
|
|
// Start is called before the first frame update
|
void Start()
|
{
|
|
}
|
|
// Update is called once per frame
|
void Update()
|
{
|
|
}
|
|
public void connectTcp()
|
{
|
try
|
{
|
if( this.client == null )
|
{
|
this.ConnectServer("127.0.0.1", 9081);
|
}
|
else
|
{
|
// TEST WORK START:
|
// ²âÊÔ·¢Ëͼòµ¥µÄÏûÏ¢µ½·þÎñÆ÷¡£
|
byte[] byteSend = System.Text.Encoding.Default.GetBytes("fuckzijia");
|
this.SendMessage(byteSend);
|
|
byte[] intArr = new byte[8];
|
for( int ti = 0;ti<8;ti ++)
|
intArr[ti] = (byte)ti;
|
|
this.SendMessage(intArr);
|
}
|
}
|
catch (Exception e)
|
{
|
Debug.Log("³ö´í:" + e.ToString());
|
}
|
|
}
|
|
/// <summary>
|
/// Á¬½Ó·þÎñÆ÷
|
/// </summary>
|
public void ConnectServer(string host, int port)
|
{
|
// ½¨Á¢ÐµÄÁ¬½Ó
|
client = new TcpClient();
|
client.SendTimeout = 1000;
|
client.ReceiveTimeout = 1000;
|
client.NoDelay = true;
|
try
|
{
|
client.BeginConnect(host, port, new AsyncCallback(OnConnect), client);
|
}
|
catch (Exception e)
|
{
|
Debug.Log("Á¬½Ó³ö´í:" + e.ToString());
|
}
|
}
|
|
void OnConnect(IAsyncResult asr)
|
{
|
TcpClient client = (TcpClient)asr.AsyncState;
|
bool validConn = (client == this.client);
|
try
|
{
|
// ½áÊøÒì²½Á¬½Ó
|
client.EndConnect(asr);
|
|
// ·Çµ±Ç°Á¬½Ó
|
if (!validConn)
|
{
|
client.Close();
|
}
|
|
if (client.Connected)
|
{
|
|
// Òì²½¶ÁsocketÊý¾Ý
|
socketStream = client.GetStream();
|
socketStream.BeginRead(byteBuffer, 0, MAX_READ, new AsyncCallback(OnRead), new SocketState(client, socketStream));
|
Debug.Log("Async Connect TcpServer Success.");
|
}
|
else
|
{
|
Debug.Log("client connect failed.");
|
}
|
}
|
catch (SocketException e)
|
{
|
Debug.Log("Á¬½ÓÖ®ºó£¬³öÎÊÌâÁË:" + e.ToString());
|
}
|
}
|
|
/// <summary>
|
/// ¶ÁÈ¡ÏûÏ¢
|
/// </summary>
|
void OnRead(IAsyncResult asr)
|
{
|
int bytesRead = 0; // ¶ÁÈ¡µ½µÄ×Ö½Ú
|
bool validConn = false; // ÊÇ·ñÊǺϷ¨µÄÁ¬½Ó
|
|
Debug.Log("Read Message is Called.");
|
|
SocketState socketState = (SocketState)asr.AsyncState;
|
TcpClient client = socketState.client;
|
if (client == null || !client.Connected)
|
{
|
return;
|
}
|
try
|
{
|
validConn = (client == this.client);
|
NetworkStream socketStream = socketState.socketStream;
|
|
// ¶ÁÈ¡×Ö½ÚÁ÷µ½»º³åÇø
|
bytesRead = socketStream.EndRead(asr);
|
|
if (bytesRead < 1)
|
{
|
if (!validConn)
|
{
|
// ÒÑ¾ÖØÐÂÁ¬½Ó¹ýÁË
|
socketStream.Close();
|
client.Close();
|
}
|
else
|
{
|
// ±»¶¯¶Ï¿ªÊ±
|
// ֪ͨÁ¬½Ó±»¶Ï¿ª
|
//OnDisconnected(DisType.Disconnect, "bytesRead < 1");
|
}
|
return;
|
}
|
|
// ½ÓÊÜÊý¾Ý°ü£¬Ð´È뻺³åÇø
|
OnReceive(byteBuffer, bytesRead);
|
|
// ÔٴμàÌý·þÎñÆ÷·¢¹ýÀ´µÄÐÂÏûÏ¢
|
Array.Clear(byteBuffer, 0, byteBuffer.Length); //Çå¿ÕÊý×é
|
socketStream.BeginRead(byteBuffer, 0, MAX_READ, new AsyncCallback(OnRead), socketState);
|
}
|
catch (Exception e)
|
{
|
//Log.Instance.errorFormat("read data error, connect valid:{0}", e, validConn);
|
Debug.Log("³öÏÖÁËÒì³££º" + e.ToString());
|
if (validConn)
|
{
|
// ֪ͨÁ¬½Ó±»¶Ï¿ª
|
//OnDisconnected(DisType.Exception, e);
|
}
|
else
|
{
|
socketStream.Close();
|
client.Close();
|
}
|
}
|
|
// ¶ÔÏûÏ¢½øÐнâÂë
|
if (bytesRead > 0)
|
{
|
// OnDecodeMessage();
|
}
|
}
|
|
private void OnReceive(byte[] byteBuffer, int bytesRead)
|
{
|
//throw new NotImplementedException();
|
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
|
string msgReceive = ascii.GetString(byteBuffer);
|
Debug.Log("¿Í»§¶ËÊÕµ½ÏûÏ¢:" + msgReceive);
|
}
|
|
/// <summary>
|
/// ·¢ËÍÏûÏ¢
|
/// </summary>
|
public bool SendMessage( byte[] barr )
|
{
|
try
|
{
|
bool ret = WriteMessage( barr );
|
return ret;
|
}
|
catch (Exception e)
|
{
|
Debug.Log("·¢ËÍÏûÏ¢³ö´í:" + e.ToString() );
|
}
|
return false;
|
}
|
/// <summary>
|
/// дÊý¾Ý
|
/// </summary>
|
bool WriteMessage(byte[] message)
|
{
|
bool ret = true;
|
|
if (null != socketStream)
|
{
|
socketStream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), socketStream);
|
ret = true;
|
}
|
else
|
{
|
Debug.Log("write data, but socket not connected");
|
ret = false;
|
}
|
|
return ret;
|
}
|
|
/// <summary>
|
/// ÏòÁ´½ÓдÈëÊý¾ÝÁ÷
|
/// </summary>
|
void OnWrite(IAsyncResult r)
|
{
|
NetworkStream tsocketStream = null;
|
try
|
{
|
tsocketStream = (NetworkStream)r.AsyncState;
|
socketStream.EndWrite(r);
|
Debug.Log("·¢ËÍÏûÏ¢µ½·þÎñÆ÷³É¹¦.");
|
}
|
catch (Exception e)
|
{
|
if ((e is IOException) && tsocketStream == this.socketStream)
|
{
|
// IO Òì³£²¢ÇÒ»¹Êǵ±Ç°Á¬½Ó
|
//OnDisconnected(DisType.Exception, e);
|
}
|
}
|
}
|
|
/// <summary>
|
/// ¹ØÓÚÍøÂç¶ÏÏߵĴ¦Àí
|
/// </summary>
|
void OnDisconnected()
|
{
|
|
}
|
|
|
// ÁíÍâÒ»¸ö±ØÐëÒª´¦ÀíµÄÊÇtcpµÄÕ³°ü£¬Õâ¸öÊDZØÐëÒª´¦ÀíµÄÄÚÈÝ
|
|
|
/// <summary>
|
/// ¼ì²ésocket״̬
|
/// </summary>
|
/// <returns><c>true</c>, if socket was checked, <c>false</c> otherwise.</returns>
|
public bool CheckSocketState()
|
{
|
//Log.Instance.info("check socket state start");
|
|
// socketÁ÷Ϊ¿Õ
|
if (client == null)
|
{
|
return true;
|
}
|
|
// ²»ÔÚÁ¬½Ó״̬
|
if (!client.Connected)
|
{
|
//Log.Instance.info("check socket state end, socket is not connected");
|
return false;
|
}
|
|
// ÅжÏÁ¬½Ó״̬
|
bool connectState = true;
|
Socket socket = client.Client;
|
bool blockingState = socket.Blocking;
|
try
|
{
|
byte[] tmp = new byte[1];
|
|
socket.Blocking = false;
|
socket.Send(tmp, 0, 0);
|
connectState = true; // ÈôSend´íÎó»áÌøÈ¥Ö´ÐÐcatchÌ壬¶ø²»»áÖ´ÐÐÆätryÌåÀïÆäÖ®ºóµÄ´úÂë
|
|
//Log.Instance.info("check socket state succ");
|
}
|
catch (SocketException e)
|
{
|
//Log.Instance.warnFormat("check socket error, errorCode:{0}", e.NativeErrorCode);
|
|
// 10035 == WSAEWOULDBLOCK
|
if (e.NativeErrorCode.Equals(10035))
|
{
|
// Still Connected, but the Send would block
|
connectState = true;
|
}
|
else
|
{
|
// Disconnected
|
connectState = false;
|
}
|
}
|
finally
|
{
|
socket.Blocking = blockingState;
|
}
|
|
return connectState;
|
}
|
|
}
|