C#中Socket與Unity相結(jié)合示例代碼
前言
初步接觸了Socket,現(xiàn)使其與Unity相結(jié)合,做成一個(gè)簡(jiǎn)單的客戶端之間可以互相發(fā)送消息的一個(gè)Test。下面話不多說了,來一起看看詳細(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ù)組,用來存儲(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 "無法獲得地址";
}
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è)連接類,用來維護(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)單的頁面,通過下面的代碼你可以了解需要哪些組件
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à)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
DevExpress之ChartControl實(shí)現(xiàn)餅狀圖百分比演示實(shí)例
這篇文章主要介紹了DevExpress之ChartControl實(shí)現(xiàn)餅狀圖百分比演示的方法,實(shí)例講述了窗體與圖形繪制函數(shù)的用法,需要的朋友可以參考下2014-10-10
C#串口編程System.IO.Ports.SerialPort類
這篇文章介紹了C#串口編程System.IO.Ports.SerialPort類,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
C#實(shí)現(xiàn)Check Password和鎖定輸錯(cuò)密碼鎖定賬戶功能
C#實(shí)現(xiàn)的Check Password,并根據(jù)輸錯(cuò)密碼的次數(shù)分情況鎖定賬戶:如果輸入錯(cuò)誤3次,登錄賬戶鎖定5分鐘并提示X點(diǎn)X分后重試登錄,具體實(shí)現(xiàn)代碼感興趣的朋友跟隨小編一起看看吧2020-01-01
C#結(jié)合數(shù)據(jù)庫實(shí)現(xiàn)驗(yàn)證識(shí)別ID卡內(nèi)容的方法
這篇文章主要介紹了C#結(jié)合數(shù)據(jù)庫實(shí)現(xiàn)驗(yàn)證識(shí)別ID卡內(nèi)容的方法,非常實(shí)用的功能,需要的朋友可以參考下2014-07-07

