본문 바로가기
IT/유니티

유니티 게임 프로그래밍 9장 예제 구현

by nutrient 2021. 5. 30.
728x90
728x170

 

Log

using UnityEngine;
using System.Collections;

public class Log : MonoBehaviour {

	public GUISkin skin;
	public int ScrollSize;
	private int index = 0;
	private Vector2 scrollPosition = Vector2.zero;
	
	private string[] logtext;
	
	public static Log logInstance;
	
	public bool ison = false;
	
	void Awake() {
		
			logInstance = this;
			DontDestroyOnLoad(transform.gameObject);
				
	}
	
	void Start () {
		if(ScrollSize == 0)
		{
			ScrollSize = 1000;
		}
		logtext = new string[ScrollSize];
		for(int i = 0 ; i < ScrollSize ; i++)
		{
			logtext[i] = " ";
		}        
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void OnGUI()
    {
        if (GUI.Button(new Rect(0, 0, 48, 16), "X"))
        {
            index = 0;
            for (int i = 0; i < ScrollSize; i++)
            {
                logtext[i] = " ";
            }

            scrollPosition = Vector2.zero;
        }
        

		ison = GUI.Toggle(new Rect(100, 0, 100, 24), ison, "On/Off");
		if(ison.Equals(true))
		{
		//	GUI.skin = skin;            
		
			//GUILayout.BeginArea( new Rect(10, 100, 700, 500));
			scrollPosition = GUI.BeginScrollView(new Rect(10, 50, Screen.width-10, Screen.height-50), scrollPosition, new Rect(0, 0, 1000, ScrollSize * 24));

        
        	GUI.color = Color.red;
        	for(int i = 0; i < ScrollSize ; i++ )
			{
				//GUILayout.Label (logtext[i]);	
				GUI.Label(new Rect(0, i * 28, 700, 28), logtext[i]);
			}
			GUI.EndScrollView();

      	  	//GUILayout.EndArea();
		}
	}
	
	public void ScreenLog(string text)
	{
		if(logtext == null)
			return;
		
		logtext[index] = text;
		index++;
		if(index > ScrollSize - 1)
		{
			for(int i = 0 ; i < ScrollSize - 1 ; i++)
			{
				logtext[i] = logtext[i+1];
			}
			index = ScrollSize - 1;
		}
	}
	
	public void SetOnOff(bool onoff)
	{
		this.ison = onoff;
	}
}

 

MessageData

using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[System.Serializable]
public class MessageData {

    public string stringData = "";
    public float  mousex = 0;
    public float  mousey = 0;
    public int    type = 0;
    
    public static MessageData FromByteArray(byte[] input)
    {
        // Create a memory stream, and serialize.
        MemoryStream stream = new MemoryStream(input);
        // Create a binary formatter.
        BinaryFormatter formatter = new BinaryFormatter();
    
        MessageData data = new MessageData();
        data.stringData = (string)formatter.Deserialize(stream);
        data.mousex = (float)formatter.Deserialize(stream);
        data.mousey = (float)formatter.Deserialize(stream);
        data.type = (int)formatter.Deserialize(stream);
    
        return data;
    }

    public static byte[] ToByteArray (MessageData msg)
    {
        // Create a memory stream, and serialize.
        MemoryStream stream = new MemoryStream();
        // Create a binary formatter.
        BinaryFormatter formatter = new BinaryFormatter();
    
        // Serialize.
        formatter.Serialize(stream, msg.stringData);
        formatter.Serialize(stream, msg.mousex);
        formatter.Serialize(stream, msg.mousey);
        formatter.Serialize(stream, msg.type);
        
        // Now return the array.
        return stream.ToArray();
    }


}

 

SimpleClient

using UnityEngine;

using System.Collections;
using System.Net.Sockets;
using System.Net;

public class SimpleClient : MonoBehaviour {
    
    public string m_IPAdress = "127.0.0.1";
    public const int kPort = 10253;

    private static SimpleClient singleton;

    
    private Socket m_Socket;
    void Awake ()
    {
        m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        
        System.Net.IPAddress    remoteIPAddress  = System.Net.IPAddress.Parse(m_IPAdress);
        
        System.Net.IPEndPoint   remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, kPort);

        singleton = this;
        m_Socket.Connect(remoteEndPoint);
		Log.logInstance.ScreenLog("Connecting");
    }
    
    void OnApplicationQuit ()
    {
        m_Socket.Close();
        m_Socket = null;
    }
	
	void Update()
	{
		if(Input.GetMouseButtonUp(0))
		{
			MessageData newmsg = new MessageData();
			newmsg.stringData ="hello";
			newmsg.mousex = Input.mousePosition.x;
			newmsg.mousey = Input.mousePosition.y;
			newmsg.type = 0;
			SimpleClient.Send(newmsg);
		}
	}
    
    static public void Send(MessageData msgData)
    {
        if (singleton.m_Socket == null)
            return;
            
        byte[] sendData = MessageData.ToByteArray(msgData);
        byte[] prefix = new byte[1];
        prefix[0] = (byte)sendData.Length;
        singleton.m_Socket.Send(prefix);
        singleton.m_Socket.Send(sendData);
		//Log
		Log.logInstance.ScreenLog( msgData.stringData + " " + msgData.mousex.ToString() + " " +msgData.mousey.ToString() );
    }


}

 

SimpleServer

using UnityEngine;

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


public class SimpleServer : MonoBehaviour {

    static SimpleServer singleton;
    
    private Socket m_Socket;
    
    ArrayList m_Connections = new ArrayList ();
    
    ArrayList m_Buffer = new ArrayList ();
    ArrayList m_ByteBuffer = new ArrayList ();
    
    void Awake ()
    {
        m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     
        IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any , SimpleClient.kPort);

        m_Socket.Bind( ipLocal );
		
        //start listening...
        m_Socket.Listen (100);
        singleton = this;
		
    }
	
	void Start()
	{
		Log.logInstance.ScreenLog("start listening...");


	
	}
    
    void OnApplicationQuit ()
    {
        Cleanup();
    }
    
    void Cleanup ()
    {
        if (m_Socket != null)
            m_Socket.Close();
        m_Socket = null;
    
        foreach (Socket con in m_Connections)
            con.Close();
        m_Connections.Clear();
    }   
    ~SimpleServer ()
    {
        Cleanup();      
    }
    
    void Update ()
    {
        // Accept any incoming connections!
        ArrayList listenList = new ArrayList();
        listenList.Add(m_Socket);
        Socket.Select(listenList, null, null, 1000);
        for( int i = 0; i < listenList.Count; i++ )
        {
            Socket newSocket = ((Socket)listenList[i]).Accept();
            m_Connections.Add(newSocket);
            m_ByteBuffer.Add(new ArrayList());
            Debug.Log("Did connect");
			Log.logInstance.ScreenLog("Did connect");
        }
        
        // Read data from the connections!
        if (m_Connections.Count != 0)
        {
            ArrayList connections = new ArrayList (m_Connections);
            Socket.Select(connections, null, null, 1000);
            // Go through all sockets that have data incoming!
            foreach (Socket socket in connections)
            {
                byte[] receivedbytes = new byte[512];
                
                ArrayList buffer = (ArrayList)m_ByteBuffer[m_Connections.IndexOf(socket)];
                int read = socket.Receive(receivedbytes);
                for (int i=0;i<read;i++)
                    buffer.Add(receivedbytes[i]);
                
                while (true && buffer.Count > 0)
                {
                    int length = (byte)buffer[0];
                    
                    if (length < buffer.Count)
                    {
                        ArrayList thismsgBytes = new ArrayList(buffer);
                        thismsgBytes.RemoveRange(length + 1, thismsgBytes.Count - (length + 1));
                        thismsgBytes.RemoveRange(0, 1);
                        if (thismsgBytes.Count != length)
                            Debug.Log("Bug");
                        
                        buffer.RemoveRange(0, length + 1);
                        byte[] readbytes = (byte[])thismsgBytes.ToArray(typeof(byte));

                        MessageData readMsg = MessageData.FromByteArray(readbytes);
                        m_Buffer.Add(readMsg);
                        
                        Debug.Log(System.String.Format("Message {0}: {1}, {2}", readMsg.stringData, readMsg.mousex, readMsg.mousey));
                        Log.logInstance.ScreenLog(System.String.Format("Message {0}: {1}, {2}", readMsg.stringData, readMsg.mousex, readMsg.mousey));
						
                        if (singleton != this)
                            Debug.LogError("Bug");   
                    }
                    else
                        break;
                }
                

            }           
        }
    }
    
    static public MessageData PopMessage ()
    {
        if (singleton.m_Buffer.Count == 0)
        {
            return null;
        }
        else
        {
            MessageData readMsg = (MessageData)singleton.m_Buffer[0];
            singleton.m_Buffer.RemoveAt(0);
            Debug.Log(System.String.Format("Message {0}: {1}, {2}", readMsg.stringData, readMsg.mousex, readMsg.mousey));
			Log.logInstance.ScreenLog(System.String.Format("Message {0}: {1}, {2}", readMsg.stringData, readMsg.mousex, readMsg.mousey));
            return readMsg;
        }
    }


}
728x90
그리드형

댓글