2022-2 응용프로그래밍 HW4 전기전자공학부

                                                                                                            2018142125

                                                                                                                  조정빈

1. .cs script

1-1. Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// TCP stuff
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
using TMPro;

public class HW4 : MonoBehaviour
{

    // TCP stuff
    Thread receiveThread;
    TcpClient client;
    TcpListener listener;
    int port = 9999;

    //
    //text_obj는 unity scene에 띄워져 있는 TextMeshProUGUI object로
    //할당함
    public TextMeshProUGUI text_obj;

    //temp_txt는 null로 initiate해 놓고 TCP통신을 통해 받은 string을 여기에
    //저장한다
    private string temp_text = null;

    //

    // Start is called before the first frame update
    void Start()
    {
        InitTCP();
        //
        //게임 시작시 scene에 띄어져 있는 text를 아래와 같이 설정
        text_obj.text = "this is after running unity";

        //
    }
    // Launch TCP to receive message from python
    private void InitTCP()
    {
        receiveThread = new Thread(new ThreadStart(ReceiveData));
        receiveThread.IsBackground = true;
        receiveThread.Start();
    }

    private void ReceiveData()
    {
        try
        {
            print("Waiting");
            listener = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
            listener.Start();
            Byte[] bytes = new Byte[1024];

            while (true)
            {
                using (client = listener.AcceptTcpClient())
                {
                    using (NetworkStream stream = client.GetStream())
                    {
                        int length;
                        while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            var incommingData = new byte[length];
                            Array.Copy(bytes, 0, incommingData, 0, length);
                            string clientMessage = Encoding.ASCII.GetString(incommingData);
                            //
                            temp_text = clientMessage;
                            //
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            print(e.ToString());
        }
    }

    // Update is called once per frame
    void Update()
    {
        //temp_text가 바뀌면, 즉 TCP통신을 통해
        //client에서 message가 오게 되면 text_obj의 text를 client에서 온
        //message로 바꿈
        if(temp_text != null)
        {
        text_obj.text = temp_text;
        }
        //
    }

    void OnApplicationQuit()
    {
        // close the thread when the application quits
        receiveThread.Abort();
    }
}

1-2. 동작 원리 서술

Class 변수

Thread receiveThread; //Thread object로
TcpClient client; //TCPclient object
TcpListener listener; 
//server의 port를 9999로 initate
int port = 9999;
//text_obj는 unity scene에 띄워져 있는 TextMeshProUGUI object로 할당함
public TextMeshProUGUI text_obj;
//temp_txt는 null로 initiate해 놓고 TCP통신을 통해 받은 string을 여기에 저장한다
private string temp_text = null;

Class 함수

  1. start()
void Start()
{
			  //게임 시작시 바로 InitTCP()함수를 실행한다
        InitTCP();
        
        //게임 시작시 scene에 띄어져 있는 text를 아래와 같이 설정
        text_obj.text = "this is after running unity";

        //
 }

Untitled

unity를 실행하기 전화면.

Untitled

unity 가 실행되면 가장 먼저 start()함수를 실행하게 되는데 그러면 다음과 같은 scene이 나타난다.

  1. InitTCP()
private void InitTCP()
    {
        receiveThread = new Thread(new ThreadStart(ReceiveData));
        receiveThread.IsBackground = true;
        receiveThread.Start();
    }

receiveThread에 새로운 Thread 객체를 생성해 할당하고 해당 thread를 start한다.

  1. ReceiveData()
private void ReceiveData()
    {
        try
        {
            print("Waiting");
            listener = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
            listener.Start();
            Byte[] bytes = new Byte[1024];

            while (true)
            {
                using (client = listener.AcceptTcpClient())
                {
                    using (NetworkStream stream = client.GetStream())
                    {
                        int length;
                        while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            var incommingData = new byte[length];
                            Array.Copy(bytes, 0, incommingData, 0, length);
                            string clientMessage = Encoding.ASCII.GetString(incommingData);
                            //
                            temp_text = clientMessage;
                            //
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            print(e.ToString());
        }
    }

TCP listener 를 통해 server의 IP address와 해당 port번호로 들어오는 통신을 기다린다. 만약 통신이 오면 client를 accept하고 client가 보낸 데이터를 stream으로 읽는다. 그후 들어온 clientMessage를 temp_text에 넣어둔다.

  1. Update()