SoFunction
Updated on 2025-03-06

Sample code for combining Socket and Unity in C#

Preface

I have initially contacted Socket, and now I combine it with Unity to create a simple test where clients can send messages to each other. I won’t say much below, let’s take a look at the detailed introduction together.

The method is as follows:

First, the server-side code.

Create a connection pool that stores the number of clients.

using System;
using ;
using ;
using ;
using ;


namespace Server
{
 /// <summary>
 /// Object pool /// </summary>
 public class Conn
 {
  //Constant, used to represent the maximum number of bytes transmitted and the maximum number of bytes received  public const int buffer_Size = 1024;

  //Socket
  public Socket socket;

  //Whether to connect  public bool isUse = false;

  //Transfer arrays to store received data  public byte[] readBuff = new byte[buffer_Size];


  public int buffCount = 0;

  /// <summary>
  /// Constructor  /// </summary>
  public Conn()
  {
   readBuff = new byte[buffer_Size];
  }

  /// <summary>
  /// Initialization  /// </summary>
  /// <param name="socket"></param>
  public void Init(Socket socket)
  {
    = socket;
   isUse = true;
   buffCount = 0;
  }

  /// <summary>
  /// The number of bytes remaining in the buffer  /// </summary>
  /// <returns></returns>
  public int BuffRemain()
  {
   return buffer_Size - buffCount;
  }

  /// <summary>
  /// Get the client address  /// </summary>
  /// <returns></returns>
  public string GetAdress()
  {
   if (!isUse)
   {
    return "Unable to obtain address";
   }
   else
   {
    return ();
   }

  }

  /// <summary>
  /// Close the connection  /// </summary>
  public void Close()
  {
   if (!isUse)
   {
    return;

   }
   else
   {
    ("Disconnect" + GetAdress());
    ();
    isUse = false;
   }
  }
 }
}

After the object pool is created, a connection class needs to be created to maintain the client's connection.

using System;
using ;
using ;
using ;
using ;
using ;
 

namespace Server
{
 class Serv
 {
  // Listen to sockets  public Socket listenfd;

  //Client link  public Conn[] conns;

  //Maximum number of connections  public int maxConn = 50;

  //Get the link pool index, return a negative number to indicate the acquisition failed  public int NewIndex()
  {
   if(conns==null)
   {
    return -1;
   }
   for (int i = 0; i < ;i++ )
   {
    if(conns[i]==null)
    {
     conns[i] = new Conn();
     return i;
    }else if(conns[i].isUse==false)
    {
     return i;
    }
   }
   return -1;
  }

  //Open a server  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(, , );

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

   //Associated with a local endpoint   (ipEp);

   //monitor   (maxConn);

   (AcceptCb, listenfd);

  }

  //AcceptCb callback  public void AcceptCb(IAsyncResult ar)
  {
   try
   {
    Socket sSocket =  as Socket;
    Socket socket = (ar);

    int index = NewIndex();
    if(index<0)
    {
     ();
     ("Connection full");
    }
    else
    {
     Conn conn = conns[index];
     (socket);
     string adr = ();
     ("Client Connection[" + adr + "Conn Pool ID: " + index);

     (, , (), , ReceiveCb, conn);

    }

    (AcceptCb, listenfd);


   }catch(SocketException ex)
   {
    (ex);
   }

  }

  //ReceiveCb callback  public void ReceiveCb(IAsyncResult ar)
  {
   Conn conn = (Conn);
   try
   {
    int count = (ar);
    if(count<=0)
    {
     ("receive:" + () + "Disconnect");
     ();
     return;
    }
    string str = Encoding.(,0,count);
    ("Received[" + () + "]data" + str);

    byte[] bytes = Encoding.(str);

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

     if (!conns[i].isUse)
      continue;
     ("Transfer Message to" + conns[i].GetAdress());
     conns[i].(bytes);
    }
    (, , (), ,ReceiveCb, conn);

   }
   catch(SocketException ex)
   {
    (ex);
    ("receive:" + () + "Disconnect");
    ();
   }

  }
 }
}

Finally, create a Unity project and build a simple page. Through the following code, you can understand which components are needed.

using UnityEngine;
using ;
using ;
using ;
using ;
using ;
using System;

public class net : MonoBehaviour
{
 //IP and port public InputField hostInput;
 public InputField portInput;

 //Show the message accepted by the client public Text recvText;
 public string recvStr;

 //Show client IP and port public Text clientText;

 //Chat input box public InputField TextInput;

 Socket socket;

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


 void FixedUpdate()
 {
   = recvStr;
 }


 //Connect the server (need a Button trigger) public void Connetion()
 {
   = "";

  socket = new Socket(, , );

  string host = ;
  int port = ();

  (host, port);
   = "Client Address:"+();
  (readBuff, 0, buffer_Size, , ReceiveCb,socket);

 }

 /// <summary>
 /// Accept data /// </summary>
 /// <param name="ar"></param>
 public void ReceiveCb(IAsyncResult ar)
 {
  
  try
  {
   int count = (ar);

   string str = .(readBuff, 0, count);

   if ( > 300) recvStr = "";

   recvStr += ()+str + "\n";
   ("12346");
   (readBuff, 0, buffer_Size, , ReceiveCb, socket);
  }catch(SocketException ex)
  {
   (ex);
  }
 }

 /// <summary>
 /// Send data, (need a Button trigger) /// </summary>
 public void Send()
 {
  string str = ;
  byte[] tex = .(str);
  try
  {
   (tex);
  
  }
  catch(SocketException ex)
  {
   (ex);
  }
 }
}

The above content is from Teacher Luo Peiyu’s book “Unity3d Online Game Practical Battle”.

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.