close

 

撰寫 C# Socket Client 不難

網路上 Google C# Socket 可以找到不少範例

難的是如何處理封包上更有效率

還有驗證,加密,定義封包格式規則等等。

更多功能就靠自己去摸索吧

參考以下範例

建立接收的部分Code 可以改到 Connect 執行

懶得再改程式碼了, 請自己移動吧

Define.cs 

 

 
  using UnityEngine;
  using System.Collections;

  public class Define {
	public const string IP = "127.0.0.1";
	public const int Port = 8080;
  }

 

Example_Socket.cs

 
  using UnityEngine;
  using System.Collections;

  public class Example_Socket : MonoBehaviour {

	private SocketMgr mSocketMgr;

	void Start () {
		mSocketMgr = new SocketMgr();
	}

	public void OnClickConnect() {
		mSocketMgr.Connect(Define.IP, Define.Port);
	}

	public void OnClickClose() {
		mSocketMgr.Close();
	}

	public void OnClickSend() {
		mSocketMgr.SendServer("{Test:123456}");
	}
  }

 

SocketMgr.cs

 
  using UnityEngine;
  using System;
  using System.Collections;
  using System.Text;
  using System.Net;
  using System.Net.Sockets;

  public class SocketMgr {

	private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
	private byte[] _recieveBuffer = new byte[2048];

	public SocketMgr() {

	}
	/// 
	/// 建立 Connect Server.
	/// 
	public void Connect(string IP, int Port) {
		try
		{
			_clientSocket.Connect(new IPEndPoint(IPAddress.Parse(IP), Port));
		}
		catch(SocketException ex)
		{
			Debug.Log(ex.Message);
		}
	}
	/// 
	/// 發送到 Server & 啟動接收
	/// 
	public void SendServer(String sJson) {
		try
		{
			byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(sJson);
			SendData(byteArray);
		}
		catch(SocketException ex)
		{
			Debug.LogWarning(ex.Message);
		}
		_clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
	}
	/// 
	/// 發送封包到 Socket Server 
	/// 
	private void SendData(byte[] data)
	{
		SocketAsyncEventArgs socketAsyncData = new SocketAsyncEventArgs();
		socketAsyncData.SetBuffer(data,0,data.Length);
		_clientSocket.SendAsync(socketAsyncData);
	}
	/// 
	/// 接收封包.
	/// 
	private void ReceiveCallback(IAsyncResult AR)
	{
		int recieved = _clientSocket.EndReceive(AR);
		
		Debug.Log("ReceiveCallback - recieved: " + recieved + " bytes");
		
		if(recieved <= 0)
			return;

		byte[] recData = new byte[recieved];
		Buffer.BlockCopy(_recieveBuffer,0,recData,0,recieved);

		string recvStr = Encoding.UTF8.GetString(recData, 0, recieved);
		Debug.Log("recvStr: " + recvStr);

		_clientSocket.BeginReceive(_recieveBuffer,0,_recieveBuffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
	}
	/// 
	/// 關閉 Socket 連線.
	/// 
	public void Close() {
		_clientSocket.Shutdown(SocketShutdown.Both);
		_clientSocket.Close();
	}
  }

 

範例下載 Example_Socket By Unity 5.6.4f1. 

 

歡迎光臨 ~ Eg 程式筆記的天堂
當你看完此篇文章,如果你覺得文章不錯
可以留下鼓勵的留言~
將是我的撰寫更多相關文章的動力

arrow
arrow
    文章標籤
    Unity Socket Client Example
    全站熱搜

    低調_Eg 發表在 痞客邦 留言(1) 人氣()