在Unity中接收服务器的推送消息

由于刚学了几天的U3d,所以想法也不成熟,只是实验一下, 希望能接收服务器的推送消息,服务器用php的,具体实现很简单,用c#开启一个线程来 来监听一个端口,这样就可以接收到服务器的消息了;

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

public class Test : MonoBehaviour
{


    private  string showMessage = "";


	// Use this for initialization
    private   byte[] resultBytes = new byte[1024];
    private  int myPort = 8885;
    private  Socket serverSocket;
    //

	void Start ()
	{
	    string hostName = Dns.GetHostName();
        
        Debug.Log(hostName);

	    System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);

	    foreach (IPAddress ipAddress in addressList)
	    {
	        Debug.Log(ipAddress.ToString());
	    }
	    showMessage += "\n" + addressList[0].ToString();
	    IPAddress ip = IPAddress.Parse(addressList[0].ToString());
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        serverSocket.Bind(new IPEndPoint(ip, myPort));
        serverSocket.Listen(10);

        Thread myThread = new Thread(ListenClientConnect);
        myThread.Start();
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    void OnGUI()
    {
        GUILayout.BeginScrollView(new Vector2(0, 0), GUILayout.Width(100));
        GUILayout.Box(showMessage);
        GUILayout.EndScrollView();
    }

    private  void ListenClientConnect()
    {
        while (true)
        {
            Socket clientSocket = serverSocket.Accept();
            clientSocket.Send(Encoding.ASCII.GetBytes("Server say Hello"));

            Thread receiveThread = new Thread(ReceiveMessage);
            receiveThread.Start(clientSocket);
        }
    }

    private  void ReceiveMessage(object clientSocket)
    {
        Debug.Log("进入ReceiveMessage");
        Socket myClientSocket = (Socket) clientSocket;

        while (true)
        {
            try
            {
                int receiveNumber = myClientSocket.Receive(resultBytes);
                string contentString = Encoding.ASCII.GetString(resultBytes, 0, receiveNumber);
                showMessage += "\n" + contentString;
                Debug.Log(contentString);
            }
            catch (Exception ex)
            {
                myClientSocket.Shutdown(SocketShutdown.Both);
                myClientSocket.Close();
                break;
            }
        }
    }
}


你可能感兴趣的:(Unity3D)