真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

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

前言

創(chuàng)新互聯(lián)建站專(zhuān)注為客戶(hù)提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于做網(wǎng)站、成都網(wǎng)站制作、浦東網(wǎng)絡(luò)推廣、成都微信小程序、浦東網(wǎng)絡(luò)營(yíng)銷(xiāo)、浦東企業(yè)策劃、浦東品牌公關(guān)、搜索引擎seo、人物專(zhuān)訪、企業(yè)宣傳片、企業(yè)代運(yùn)營(yíng)等,從售前售中售后,我們都將竭誠(chéng)為您服務(wù),您的肯定,是我們最大的嘉獎(jiǎng);創(chuàng)新互聯(lián)建站為所有大學(xué)生創(chuàng)業(yè)者提供浦東建站搭建服務(wù),24小時(shí)服務(wù)熱線:028-86922220,官方網(wǎng)址:www.cdcxhl.com

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

方法如下:

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

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

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


namespace Server
{
 /// 
 /// 對(duì)象池
 /// 
 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;

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

  /// 
  /// 初始化
  /// 
  /// 
  public void Init(Socket socket)
  {
   this.socket = socket;
   isUse = true;
   buffCount = 0;
  }

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

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

  }

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

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

對(duì)象池創(chuàng)建完成后,需要在創(chuàng)建一個(gè)連接類(lèi),用來(lái)維護(hù)客戶(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)聽(tīng)套接字
  public Socket listenfd;

  //客戶(hù)端鏈接
  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;
  }

  //開(kāi)啟一個(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)聽(tīng)
   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("連接已滿(mǎn)");
    }
    else
    {
     Conn conn = conns[index];
     conn.Init(socket);
     string adr = conn.GetAdress();
     Console.WriteLine("客戶(hù)端連接[" + 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() + "斷開(kāi)連接");
     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() + "斷開(kāi)連接");
    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;

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

 //顯示客戶(hù)端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 = "客戶(hù)端地址:"+socket.LocalEndPoint.ToString();
  socket.BeginReceive(readBuff, 0, buffer_Size, SocketFlags.None, ReceiveCb,socket);

 }

 /// 
 /// 接受數(shù)據(jù)
 /// 
 /// 
 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);
  }
 }

 /// 
 /// 發(fā)送數(shù)據(jù),(需要一個(gè)Button觸發(fā))
 /// 
 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)》一書(shū)。

總結(jié)

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


分享名稱(chēng):C#中Socket與Unity相結(jié)合示例代碼
文章起源:http://weahome.cn/article/ihpicd.html

其他資訊

在線咨詢(xún)

微信咨詢(xún)

電話咨詢(xún)

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部