IEnumerator GetCapture ()
{
yield return new WaitForEndOfFrame();
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D (width, height, TextureFormat.RGB24, false);
tex.ReadPixels (new Rect (0, 0, width, height), 0, 0, true);
byte[] imagebytes = tex.EncodeToPNG ();//转化为png图
tex.Compress (false);//对屏幕缓存进行压缩
//image.mainTexture = tex;//对屏幕缓存进行显示(缩略图)
string PicPath="storage";
File.WriteAllBytes (Application.persistentDataPath+"/"+Time.time+ ".png", imagebytes);//存储png图
path.text = Application.persistentDataPath+"/";
}
/// <summary>
/// 向服务器发送消息
/// </summary>
/// <returns>The data.</returns>
public IEnumerator sendData()
{
int i=0;
while(true)
{
string sendStr = i.ToString()+"你好 server,I am Android";
byte[] sendBytes = UTF8Encoding.UTF8.GetBytes(sendStr);
clientSocket.Send(sendBytes);
i++;
yield return new WaitForSeconds(1f);
}
}
/// <summary>
/// 得到服务器回应
/// </summary>
/// <returns>The info.</returns>
public IEnumerator getInfo()
{
while(true)
{
byte[] revBytes = new byte[1024];
int bytes = clientSocket.Receive(revBytes, revBytes.Length, 0);
string revStr ="";
//revStr += Encoding.ASCII.GetString(revBytes, 0, bytes);
revStr += UTF8Encoding.UTF8.GetString(revBytes,0,bytes);
Debug.Log ("接收到服务器消息:"+revStr);
text.text = "From Server:"+revStr;
yield return null;
}
}
}
服务器端运行结果:
服务器回送消息代码:string strSend = "Hello Android Client!" + DateTime.Now.Second;
局域网下测试没有什么问题,以后无论是做应用还是网络游戏肯定少不了的是Socket网络数据传输,多了解点网络知识还是很有必要的尤其是TCP协议,如有错误,欢迎指正。