Unity 簡易聊天室(基於TCP)(2)

客戶端用Unity開發,主要就是搭建一下聊天室的UI界面:輸入框,聊天內容顯示框,發送按鈕服務器

 

灰色背景的就是Message,也就是聊天內容的顯示框,是一個Text類型,這裏建立UI方面就很少講了socket

 

 在Canvas下掛一個ChatManager腳本函數

 

using System;
using UnityEngine;
using System.Net.Sockets;
using System.Net;
using UnityEngine.UI;
using System.Text;線程

public class ChatManager : MonoBehaviour {
  private Socket clientSocket;3d

  private Button btn;
  private InputField inputField;
  private Text showMessage;orm

  private byte[] data = new byte[1024];blog

  private string msg = "";ip

  void Start()
  {開發

    //建立一個socket,綁定和服務器同樣的ip和端口號,而後執行Connect就能夠鏈接上服務器了(服務器已經運行)
    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6688));input

    btn = transform.Find("Button").GetComponent<Button>();
    btn.onClick.AddListener(OnSendClick);

    inputField = transform.Find("InputField").GetComponent<InputField>();
    showMessage = transform.Find("BG/Message").GetComponent<Text>();

    ClientStart();
  }

  void Update()
  {

    if(msg!=null && msg != "")
    {
      showMessage.text += msg+"\n";回調函數不能調用Unity的組件、UI;因此只能在Update裏用,而不能直接在ReceiveCallBack(回調函數不屬於Unity的主線程)
      msg = "";
    }
  }

 

  private void OnSendClick()  //綁定到發送按鈕的方法
  {
    if (inputField.text != "")
    {
      byte[] databytes = Encoding.UTF8.GetBytes(inputField.text);
      clientSocket.Send(databytes);
      inputField.text = "";
    }
  }


  private void ClientStart()  //開始接收從服務器發來的消息
  {
    clientSocket.BeginReceive(data, 0, 1024,SocketFlags.None, ReceiveCallBack, null);
  }

  private void ReceiveCallBack(IAsyncResult ar)
  {
    try
    {  
      if (clientSocket.Connected == false)
      {
        clientSocket.Close();
        return;
      }
      int len = clientSocket.EndReceive(ar);
      string message = Encoding.UTF8.GetString(data, 0, len);
      msg = message;
      ClientStart();  //重複接收從服務器發來的信息
    }
    catch(Exception e)
    {
      Debug.Log("ReceiveCallBack:" + e);
    }
  }

 

  void OnDestroy()
  {
    clientSocket.Close();
  }

}

相關文章
相關標籤/搜索