Unity3d 指令碼與C#Socket伺服器傳輸資料

來源:互聯網
上載者:User

標籤:family   res   type   write   intern   amp   round   ons   name   

Test.cs指令碼

---------------------------------------------------------------------------------------------------------------------------------------------------

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AssemblyCSharp;
using System.Text;
using System;
using System.Threading;

public class Test : MonoBehaviour {
  private JFSocket mJFSocket;
  // Use this for initialization
  void Start () {

    mJFSocket = JFSocket.GetInstance();
  }
  // Update is called once per frame
  void Update () {
    if(mJFSocket!=null){
      Debug.Log (mJFSocket.receive_msg);
    }
  }
}

---------------------------------------------------------------------------------------------------------------------------------------------------

SocketClientTest.cs

---------------------------------------------------------------------------------------------------------------------------------------------------

using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


namespace AssemblyCSharp
{
  public class SocketClientTest
  {
    //Socket用戶端對象
    private Socket clientSocket;
    //單例模式
    private static SocketClientTest instance;
    public string receive_msg = "";
    public static SocketClientTest GetInstance()
    {
      if (instance == null)
      {
        instance = new SocketClientTest();
      }
      return instance;
    }

    //單例的建構函式
    SocketClientTest()
    {
      //建立Socket對象, 這裡我的連線類型是TCP
      clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      //伺服器IP地址
      IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
      //伺服器連接埠
      IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, 5209);
      //這是一個非同步建立串連,當串連建立成功時調用connectCallback方法
      IAsyncResult result = clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallback), clientSocket);
      //這裡做一個逾時的監測,當串連超過5秒還沒成功表示逾時
      bool success = result.AsyncWaitHandle.WaitOne(5000, true);
      if (!success)
      {
        //逾時
        Closed();
        Debug.Log("connect Time Out");
      }
      else
      {
        //Debug.Log ("與socket建立串連成功,開啟線程接受服務端資料");
        //與socket建立串連成功,開啟線程接受服務端資料。
        Thread thread = new Thread(new ThreadStart(ReceiveSorketMsg));
        thread.IsBackground = true;
        thread.Start();
      }
    }

    private void connectCallback(IAsyncResult asyncConnect)
    {
      Debug.Log("connectSuccess");
    }

    private void ReceiveSorketMsg()
    {
      Console.WriteLine ("wait---");
      //在這個線程中接受伺服器返回的資料
      while (true)
      {
        if (!clientSocket.Connected)
        {
          //與伺服器中斷連線跳出迴圈
          Debug.Log("Failed to clientSocket server.");
          clientSocket.Close();
          break;
        }
        try
        {
          //接受資料儲存至bytes當中
          byte[] bytes = new byte[4096];
          //Receive方法中會一直等待服務端回傳訊息
          //如果沒有回傳會一直在這裡等著。
          int i = clientSocket.Receive(bytes);
          if (i <= 0)
          {
            clientSocket.Close();
            break;
          }
          Debug.Log(Encoding.ASCII.GetString(bytes, 0, i));
          if (bytes.Length > 8)
          {
            //Console.WriteLine("接收伺服器訊息:{0}", Encoding.ASCII.GetString(bytes, 0, i));
            receive_msg = Encoding.ASCII.GetString(bytes, 0, i);
          }
          else
          {
            Debug.Log("length is not > 8");
          }
        }
        catch (Exception e)
        {
          Debug.Log("Failed to clientSocket error." + e);
          clientSocket.Close();
          break;
        }
      }
    }

    //關閉Socket
    public void Closed()
    {
      if (clientSocket != null && clientSocket.Connected)
      {
        clientSocket.Shutdown(SocketShutdown.Both);
        clientSocket.Close();
      }
      clientSocket = null;
    }
  }
}

 

---------------------------------------------------------------------------------------------------------------------------------------------------

 

Socket服務端代碼:

 

using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace SocketServerTest01
{
  class Program
  {
    private static byte[] result = new byte[1024];
    private static int myProt = 5209; //連接埠
    static Socket serverSocket;
    static void Main(string[] args)
    {
      //伺服器IP地址
      IPAddress ip = IPAddress.Parse("127.0.0.1");
      serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      serverSocket.Bind(new IPEndPoint(ip, myProt)); //綁定IP地址:連接埠
      serverSocket.Listen(10); //設定最多10個排隊串連請求
      Console.WriteLine("啟動監聽{0}成功", serverSocket.LocalEndPoint.ToString());
      //通過Clientsoket發送資料
      Socket clientSocket = serverSocket.Accept();
      while (true) {
        Thread.Sleep(1000);
        SendMsg(clientSocket);
      }
    }

    /// <summary>
    /// 以每秒一次的頻率發送資料給用戶端
    /// </summary>
    /// <param name="clientSocket"></param>
    public static void SendMsg(Socket clientSocket)
    {
      try
      {
        clientSocket.Send(Encoding.ASCII.GetBytes(GetRandomData()));
      }
      catch {
        Console.WriteLine("伺服器異常");
        return;
      }
    }

    /// <summary>
    /// 產生隨機字串
    /// </summary>
    /// <returns></returns>
    private static string GetRandomData()
    {
      Random ran = new Random();
      int x = ran.Next(50,200);
      int y = ran.Next(20,100);
      int z = 1000;
      int ID = ran.Next(1,30);
      string str = "ID:"+ID+"-x:"+x+"-y:"+y+"-z:"+z;
      return str;
    }
  }
}

 

Unity3d 指令碼與C#Socket伺服器傳輸資料

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.