需要引用命名空间

 

 9:36:38
齐培良老 2018/10/9 9:36:38

齐培良老师 2018/10/09 09:36:38
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

public class WeChatSocket : MonoBehaviour
{
    Socket socket;
    public InputField InputValue;
    public Text text;
    byte[] data = new byte[1024];//接收的容器
    string message = "";//转换后的消息
                        // Use this for initialization
    void Start()
    {
        ConnetToSever();

    }
    /// <summary>
    /// 创建Socket并连接服务器IP
    /// </summary>
    void ConnetToSever()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect(new IPEndPoint(IPAddress.Parse("10.0.208.54"), 4567));
        Thread t = new Thread(ReceveMessage);
        t.Start();
    }
    public void ReceveMessage()
    {

        while (true)
        {
            int length = socket.Receive(data);
            message = Encoding.UTF8.GetString(data, 0, length);
        }

    }
    public void SendMessage()
    {
        string mess = InputValue.text;
        InputValue.text = "";
        byte[] datas = Encoding.UTF8.GetBytes(mess);
        socket.Send(datas);
    }
    // Update is called once per frame
    void Update()
    {
        if (!string.IsNullOrEmpty(message))
        {
            text.text += message + "\n";
            message = "";
        }
    }
}