Unity異步客戶端程序

網絡遊戲開發中,客戶端側常採用異步Socket的方式來處理消息,程序結構如圖:

Unity客戶端的界面如圖所示:

 

程序實現代碼:

 

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

public class Echo : MonoBehaviour
{
    //聲明Socket以及定義UGUI
	Socket socket;
    public InputField Input;
    public Text text;
	
    //緩衝區
    byte[] readbuff=new byte[1024];
    string recStr="";
	
	//異步鏈接函數
    public void Connection()
    {
        socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        socket.BeginConnect("127.0.0.1",8888,connectCallback,socket);
    }
	
	//鏈接的回調函數
    public void connectCallback(IAsyncResult ar)
    {
        try
        {
            Socket socket=(Socket) ar.AsyncState;
            socket.EndConnect(ar);
            Debug.Log("connect succed");
        }
        catch(SocketException e)
        {
            Debug.Log("socket fail"+e.ToString());
        }
        socket.BeginReceive(readbuff,0,1024,0,receivecallback,socket);
    }
	
	//接收的回調函數
    public void receivecallback(IAsyncResult ar)
    {
        try
        {
             Socket socket=(Socket) ar.AsyncState;
             int count=socket.EndReceive(ar);
             string s=System.Text.Encoding.Default.GetString(readbuff,0,count);
             recStr=s+"\n"+recStr;
             socket.BeginReceive(readbuff,0,1024,0,receivecallback,socket);
        }
        catch(SocketException e)
        {
            Debug.Log("socket receive fail"+e.ToString());
        }
    }
	
	//異步發送函數
    public void Send()
    {
        string sendStr=Input.text;
        byte[] sendbytes=System.Text.Encoding.Default.GetBytes(sendStr);
        socket.BeginSend(sendbytes,0,sendbytes.Length,0,sendcallback,socket);
    }
	
	//發送函數的回調
    private void sendcallback(IAsyncResult ar)
    {
        try
        {
            Socket socket=(Socket) ar.AsyncState;
            int count=socket.EndSend(ar);
            Debug.Log("Socket send succ ,number is:"+count);
        }
        catch(SocketException e)
        {
            Debug.Log("socket send erro:"+e.ToString());
        }
    }

    public void Update() 
    {
        text.text=recStr;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章