유니티 네트워크 (Unity Socket)

Server
------------------------------------------------------------


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

public class SocketServer : MonoBehaviour {

    Thread m_socketThread;
    volatile bool m_keepReading = false;

    Socket listener;
    Socket handler;

    void Start()
    {
        Application.runInBackground = true;
        startServer();

    }

    void startServer()
    {
        m_socketThread = new System.Threading.Thread(networkCode);
        m_socketThread.IsBackground = true;
        m_socketThread.Start();
    }

    private string getIPAddress()
    {
        IPHostEntry host;
        string localIP = "";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localIP = ip.ToString();
            }

        }
        return localIP;
    }

    void networkCode()
    {

        byte[] bytes = null;

        // host running the application.
        Debug.Log("Ip " + getIPAddress().ToString());
        IPAddress[] ipArray = Dns.GetHostAddresses(getIPAddress());
        IPEndPoint localEndPoint = new IPEndPoint(ipArray[0], 1755);

        // Create a TCP/IP socket.
        listener = new Socket(ipArray[0].AddressFamily,
            SocketType.Stream, ProtocolType.Tcp);

        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            // Start listening for connections.
            while (true)
            {
                m_keepReading = true;

                // Program is suspended while waiting for an incoming connection.
                Debug.Log("Waiting for Connection");
                handler = listener.Accept();
                Debug.Log("Client Connected");

                // An incoming connection needs to be processed.
                while (m_keepReading)
                {
                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);


                    ////////////////////////
                    // use bytes, bytesRec



                    if (bytesRec <= 0)
                    {
                        m_keepReading = false;
                        handler.Disconnect(true);
                        break;
                    }
                 
                    if (bytesRec < bytes.Length)
                    {                     
                        isRefresh = true;
                     
                        break;
                    }

                    System.Threading.Thread.Sleep(1);
                }

                System.Threading.Thread.Sleep(1);
            }
        }
        catch (System.Exception e)
        {
            Debug.Log(e.ToString());
        }
    }

    void stopServer()
    {
        m_keepReading = false;

        //stop thread
        if (m_socketThread != null)
        {
            m_socketThread.Abort();
        }

        if (handler != null && handler.Connected)
        {
            handler.Disconnect(false);
            Debug.Log("Disconnected!");
        }
    }

    void OnDisable()
    {
        stopServer();
    } 

}



Client
------------------------------------------------------------

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

public class SocketClient : MonoBehaviour {

    Socket socket;

    string ipAdress = "192.168.0.1";
    int port = 1755;

    byte[] sendByte;

    // Use this for initialization
    void Start () {

        //create socket
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


        //connect
        try
        {
            IPAddress ipAddr = IPAddress.Parse(ipAdress);
            IPEndPoint ipendPoint = new IPEndPoint(ipAddr, port);
            socket.Connect(ipendPoint);

        }
        catch(SocketException se)
        {
            Debug.Log("Socket connect error ! : " + se.ToString());

            return;
        }
}

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.A))
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Test 1 - send data!!");

                int l = Encoding.Default.GetByteCount(sb.ToString());
                byte[] d = Encoding.Default.GetBytes(sb.ToString());
                socket.Send(d, l, 0);
            }
            catch(Exception e)
            {
                Debug.Log("Socket send or receive error ! : " + e.ToString());
            }
         
            socket.Disconnect(true);
            socket.Close();
        }
    }
}

댓글

  1. Sockeet Server isRefresh 불리언은 어디에 쓰신 건가요? 선언도 안되어있는데..

    답글삭제

댓글 쓰기

이 블로그의 인기 게시물

유니티 텍스쳐 생성 (Unity Texture Create from bytes)

유니티 네트워크 (Unity NetworkManager Component)