溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C#中Socket與Unity相結(jié)合示例代碼

發(fā)布時(shí)間:2020-08-26 22:03:40 來(lái)源:腳本之家 閱讀:167 作者:青魚谷雨 欄目:編程語(yǔ)言

前言

初步接觸了Socket,現(xiàn)使其與Unity相結(jié)合,做成一個(gè)簡(jiǎn)單的客戶端之間可以互相發(fā)送消息的一個(gè)Test。下面話不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹吧。

方法如下:

首先,是服務(wù)端的代碼。

創(chuàng)建一個(gè)連接池,用于存儲(chǔ)客戶端的數(shù)量。

using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;


namespace Server
{
 /// <summary>
 /// 對(duì)象池
 /// </summary>
 public class Conn
 {
  //常量,用于表示傳輸?shù)淖止?jié)最大數(shù)量,最大接收的字節(jié)數(shù)
  public const int buffer_Size = 1024;

  //Socket
  public Socket socket;

  //是否連接
  public bool isUse = false;

  //傳輸數(shù)組,用來(lái)存儲(chǔ)接受到的數(shù)據(jù)
  public byte[] readBuff = new byte[buffer_Size];


  public int buffCount = 0;

  /// <summary>
  /// 構(gòu)造函數(shù)
  /// </summary>
  public Conn()
  {
   readBuff = new byte[buffer_Size];
  }

  /// <summary>
  /// 初始化
  /// </summary>
  /// <param name="socket"></param>
  public void Init(Socket socket)
  {
   this.socket = socket;
   isUse = true;
   buffCount = 0;
  }

  /// <summary>
  /// 緩沖區(qū)剩下的字節(jié)數(shù)
  /// </summary>
  /// <returns></returns>
  public int BuffRemain()
  {
   return buffer_Size - buffCount;
  }

  /// <summary>
  /// 獲得客戶端地址
  /// </summary>
  /// <returns></returns>
  public string GetAdress()
  {
   if (!isUse)
   {
    return "無(wú)法獲得地址";
   }
   else
   {
    return socket.RemoteEndPoint.ToString();
   }

  }

  /// <summary>
  /// 關(guān)閉連接
  /// </summary>
  public void Close()
  {
   if (!isUse)
   {
    return;

   }
   else
   {
    Console.WriteLine("斷開連接" + GetAdress());
    socket.Close();
    isUse = false;
   }
  }
 }
}

對(duì)象池創(chuàng)建完成后,需要在創(chuàng)建一個(gè)連接類,用來(lái)維護(hù)客戶端的連接。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
 

namespace Server
{
 class Serv
 {
  //監(jiān)聽套接字
  public Socket listenfd;

  //客戶端鏈接
  public Conn[] conns;

  //最大的連接數(shù)量
  public int maxConn = 50;

  //獲取鏈接池索引,返回負(fù)數(shù)表示獲取失敗
  public int NewIndex()
  {
   if(conns==null)
   {
    return -1;
   }
   for (int i = 0; i < conns.Length;i++ )
   {
    if(conns[i]==null)
    {
     conns[i] = new Conn();
     return i;
    }else if(conns[i].isUse==false)
    {
     return i;
    }
   }
   return -1;
  }

  //開啟一個(gè)服務(wù)器
  public void Start(string host,int port)
  {
   conns = new Conn[maxConn];


   for (int i = 0; i < maxConn;i++ )
   {
    conns[i] = new Conn();
   }


   listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

   IPAddress ipAdr = IPAddress.Parse(host);
   IPEndPoint ipEp = new IPEndPoint(ipAdr, port);

   //與一個(gè)本地終結(jié)點(diǎn)相關(guān)聯(lián)
   listenfd.Bind(ipEp);

   //監(jiān)聽
   listenfd.Listen(maxConn);

   listenfd.BeginAccept(AcceptCb, listenfd);

  }

  //AcceptCb回調(diào)
  public void AcceptCb(IAsyncResult ar)
  {
   try
   {
    Socket sSocket = ar.AsyncState as Socket;
    Socket socket = sSocket.EndAccept(ar);

    int index = NewIndex();
    if(index<0)
    {
     socket.Close();
     Console.WriteLine("連接已滿");
    }
    else
    {
     Conn conn = conns[index];
     conn.Init(socket);
     string adr = conn.GetAdress();
     Console.WriteLine("客戶端連接[" + adr + "Conn池ID: " + index);

     conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn);

    }

    listenfd.BeginAccept(AcceptCb, listenfd);


   }catch(SocketException ex)
   {
    Console.WriteLine(ex);
   }

  }

  //ReceiveCb回調(diào)
  public void ReceiveCb(IAsyncResult ar)
  {
   Conn conn = (Conn)ar.AsyncState;
   try
   {
    int count = conn.socket.EndReceive(ar);
    if(count<=0)
    {
     Console.WriteLine("收到:" + conn.GetAdress() + "斷開連接");
     conn.Close();
     return;
    }
    string str = Encoding.UTF8.GetString(conn.readBuff,0,count);
    Console.WriteLine("接收到[" + conn.GetAdress() + "]數(shù)據(jù)" + str);

    byte[] bytes = Encoding.UTF8.GetBytes(str);

    for (int i = 0; i < conns.Length;i++ )
    {
     if(conns[i]==null)
      continue;

     if (!conns[i].isUse)
      continue;
     Console.WriteLine("將消息傳送給" + conns[i].GetAdress());
     conns[i].socket.Send(bytes);
    }
    conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None,ReceiveCb, conn);

   }
   catch(SocketException ex)
   {
    Console.WriteLine(ex);
    Console.WriteLine("收到:" + conn.GetAdress() + "斷開連接");
    conn.Close();
   }

  }
 }
}

最后是創(chuàng)建一個(gè)Unity的工程,搭建一個(gè)簡(jiǎn)單的頁(yè)面,通過(guò)下面的代碼你可以了解需要哪些組件

using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using UnityEngine.UI;
using System.Collections.Generic;
using System;

public class net : MonoBehaviour
{
 //ip和端口
 public InputField hostInput;
 public InputField portInput;

 //顯示客戶端接受的消息
 public Text recvText;
 public string recvStr;

 //顯示客戶端IP和端口
 public Text clientText;

 //聊天輸入框
 public InputField TextInput;

 Socket socket;

 const int buffer_Size = 1024;
 public byte[] readBuff = new byte[buffer_Size];


 void FixedUpdate()
 {
  recvText.text = recvStr;
 }


 //連接服務(wù)器(需要一個(gè)Button觸發(fā))
 public void Connetion()
 {
  recvText.text = "";

  socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

  string host = hostInput.text;
  int port = int.Parse(portInput.text);

  socket.Connect(host, port);
  clientText.text = "客戶端地址:"+socket.LocalEndPoint.ToString();
  socket.BeginReceive(readBuff, 0, buffer_Size, SocketFlags.None, ReceiveCb,socket);

 }

 /// <summary>
 /// 接受數(shù)據(jù)
 /// </summary>
 /// <param name="ar"></param>
 public void ReceiveCb(IAsyncResult ar)
 {
  
  try
  {
   int count = socket.EndReceive(ar);

   string str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count);

   if (recvStr.Length > 300) recvStr = "";

   recvStr += socket.LocalEndPoint.ToString()+str + "\n";
   Debug.Log("12346");
   socket.BeginReceive(readBuff, 0, buffer_Size, SocketFlags.None, ReceiveCb, socket);
  }catch(SocketException ex)
  {
   Debug.Log(ex);
  }
 }

 /// <summary>
 /// 發(fā)送數(shù)據(jù),(需要一個(gè)Button觸發(fā))
 /// </summary>
 public void Send()
 {
  string str = TextInput.text;
  byte[] tex = System.Text.Encoding.UTF8.GetBytes(str);
  try
  {
   socket.Send(tex);
  
  }
  catch(SocketException ex)
  {
   Debug.Log(ex);
  }
 }
}

以上內(nèi)容出自羅培羽老師《unity3d網(wǎng)絡(luò)游戲?qū)崙?zhàn)》一書。

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)億速云的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI