1. 程式人生 > >【隨堂筆記】unity中socket的用法(二、伺服器與客戶端之間簡單的資料傳遞)

【隨堂筆記】unity中socket的用法(二、伺服器與客戶端之間簡單的資料傳遞)

主要實現伺服器與客戶端之間簡單的資料傳輸(單次)

伺服器程式碼

using System;
using System.Net;
using System.Net.Sockets;

namespace SeverSocket
{
    class Program
    {
        static void Main(string[] args)
        {
            //建立伺服器
            Socket severSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            //ip地址和埠號繫結
            EndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.213.54"),10001);
            //繫結伺服器
            severSocket.Bind(endPoint);

            //發起監聽
            severSocket.Listen(1000);

            Console.WriteLine("伺服器已經啟動成功!!!!");
            while (true)
            {
                Console.WriteLine("等待客戶端連結");
                Socket cilentSocket = severSocket.Accept();//這裡會阻塞,等待連結
                Console.WriteLine("有新的使用者連結!!!!");
                Console.WriteLine("請輸入要發給客戶端的內容:");
                string readLine = Console.ReadLine();
                byte[] sendMsg = System.Text.Encoding.UTF8.GetBytes(readLine);
                int sendLength= cilentSocket.Send(sendMsg,SocketFlags.None);
                Console.WriteLine("傳送訊息成功,傳送的訊息長度是:"+sendLength);

                //接收
                Console.WriteLine("開始接收訊息");
                byte[] buffer = new byte[512];
                int receivelength = cilentSocket.Receive(buffer);
                //輸出一下接收到的內容
                string receiveMsg = System.Text.Encoding.UTF8.GetString(buffer);
                Console.WriteLine("接收到的訊息是:"+receiveMsg);

            }
        }
    }
}

客戶端程式碼

using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System;
/// <summary>
/// 客戶端的控制指令碼
/// </summary>
public class ClientSocketController : MonoBehaviour {
    /// <summary>
    /// 連結物件
    /// </summary>
    public Socket clientSocket;
    /// <summary>
    /// ip地址
    /// </summary>
    public string ipAddress = "192.168.213.54";
    /// <summary>
    /// 埠號,這個是伺服器開設的埠號
    /// </summary>
    public int portNumber = 10001;
    /// <summary>
    /// 連結間隔時間
    /// </summary>
    public float connectInterval = 1;
    /// <summary>
    /// 當前連結時間
    /// </summary>
    public float connectTime = 0;
    /// <summary>
    /// 連結次數
    /// </summary>
    public int connectCount = 0;
    /// <summary>
    /// 是否在連線中
    /// </summary>
    public bool isConnecting=false;
	void Start () {
        //呼叫開始連線
        ConnectedToServer();

    }
    /// <summary>
    /// 連結到伺服器
    /// </summary>
    public void ConnectedToServer()
    {
        //連結次數增加
        connectCount++;
        isConnecting = true;
        Debug.Log("這是第"+connectCount+"次連結");
        //如果客戶端不為空
        if (clientSocket!=null)
        {
            try
            {
                //斷開連線,釋放資源
                clientSocket.Disconnect(false);
                clientSocket.Close();
            }
            catch (System.Exception e)
            {
                Debug.Log(e.ToString());
            }
            
        }                         

        //建立新的連結(固定格式)
        clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

        //設定埠號和ip地址
        EndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipAddress),portNumber);

        //發起連結
        clientSocket.BeginConnect(endPoint,OnConnectCallBack,"");
    }
    /// <summary>
    /// 開始連結的回撥
    /// </summary>
    /// <param name="ar"></param>
    public void OnConnectCallBack(IAsyncResult ar)
    {
        Debug.Log("連結完成!!!!");
        if (clientSocket.Connected)
        {
            //連結成功
            Debug.Log("連結成功");
            connectCount = 0;

            //開啟收訊息
            ReceiveFormServer();
        }
        else
        {
            //連結失敗
            Debug.Log("連結失敗");
            //計時重置
            connectTime = 0;
        }
        isConnecting = false;
        //結束連結
        clientSocket.EndConnect(ar);
    }
    /// <summary>
    /// 向伺服器傳送字串資訊
    /// </summary>
    /// <param name="msg"></param>
    public void SendMessageToServer(string msg)
    {
        //將字串轉成byte陣列
        byte[] msgBytes = System.Text.Encoding.UTF8.GetBytes(msg);
        clientSocket.BeginSend(msgBytes,0,msgBytes.Length,SocketFlags.None,SendMassageCallBack,1);
    }
    /// <summary>
    /// 傳送資訊的回撥
    /// </summary>
    /// <param name="ar"></param>
    public void SendMassageCallBack(IAsyncResult ar)
    {
        //關閉訊息傳送
        int length=clientSocket.EndSend(ar);
        Debug.Log("資訊傳送成功,傳送的資訊長度是:"+length);
    }
    /// <summary>
    /// 從伺服器接收訊息
    /// </summary>
    public void ReceiveFormServer()
    {
        //定義緩衝池
        byte[] buffer = new byte[512];
        clientSocket.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,ReceiveFormServerCallBack,buffer);
    }
    /// <summary>
    /// 資訊接收方法的回撥
    /// </summary>
    /// <param name="ar"></param>
    public void ReceiveFormServerCallBack(IAsyncResult ar)
    {
        //結束接收
       int length=clientSocket.EndReceive(ar);
        byte[] buffer = (byte[])ar.AsyncState;
        //將接收的東西轉為字串
        string msg = System.Text.Encoding.UTF8.GetString(buffer,0,length);
        Debug.Log("接收到的訊息是:"+msg);

        //開啟下一次接收訊息
        ReceiveFormServer();
    }
    void Update () {
        if (Input.GetMouseButton(0))
        {
            SendMessageToServer("吾於殺戮之中綻放,亦如黎明中的花朵!");
        }
        if (clientSocket!=null && clientSocket.Connected==false)
        {
                //連結沒有成功
                //計時
                connectTime += Time.deltaTime;
                if (connectTime > connectInterval && isConnecting == false)//如果時間大於連結重置時間間隔且沒有連結
                {
                   if (connectCount >= 7)
                   {
                       Debug.Log("已經嘗試了7次,請檢查網路連線");
                       clientSocket = null;
                   }
                   else
                   {
                      //重連一次
                      ConnectedToServer();
                   }

                }


        }
	}

    private void OnDestroy()
    {
        Debug.Log("物體被銷燬");
        //關閉客戶端
        clientSocket.Close();
    }
}

小結:伺服器與客戶端傳遞的資料格式要保持一致