/// <summary>
/// 接收消息
/// </summary>
public static void ReceiveData()
{
if (serverSocket.ReceiveBufferSize > 0)
{
serverSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
int REnd = serverSocket.EndReceive(ar);
Console.WriteLine("长度:" + REnd);
if (REnd > 0)
{
byte[] data = new byte[REnd];
Array.Copy(MsgBuffer, 0, data, 0, REnd);
int Msglen = data.Length;
//在此次可以对data进行按需处理
serverSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
//Console.WriteLine("接收服务端的信息:{0}", Encoding.ASCII.GetString(MsgBuffer, 0, Msglen));
Console.WriteLine("接收服务端的信息:{0}", UTF8Encoding.UTF8.GetString(data, 0, Msglen));
}
else
{
dispose();
}
}
catch (SocketException ex)
{ }
}
private static void dispose()
{
try
{
serverSocket.Shutdown(SocketShutdown.Both);
serverSocket.Close();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
}
移动端使用Unity3D写的脚本挂在mainCamera上,代码如下:
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System;
using System.Text;
using System.IO;
public class client : MonoBehaviour
{
public GUIText text;
public GUIText path;
public static Socket clientSocket;
// Use this for initialization
void Start ()
{
//服务器IP
string LocalIP = "192.168.1.100";
//端口号
int port = 121;
IPAddress ip =IPAddress.Parse(LocalIP);
IPEndPoint ipe = new IPEndPoint(ip,port);
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立客户端Socket
clientSocket.Connect(ipe);
StartCoroutine("sendData"); //启动协同程序
StartCoroutine("getInfo");
}
// Update is called once per frame
void Update ()
{
if(Input.GetKey(KeyCode.Escape)||Input.GetKey(KeyCode.Home))
{
Application.Quit();
}
}
void OnGUI()
{
if(GUI.Button(new Rect(Screen.width/2-40,30,100,60),"截图"))
{
StartCoroutine("GetCapture");
}
}