반응형

 

 

 

- Client Socket  코드

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
public enum NetKind { Connect, Disconnect, Move, }

public delegate void DelSocketReceive(byte[] packet);

public class ClientSocket
{
    private Socket NetSocket;
    EndPoint severEndPoint;

    private DelSocketReceive CallbackReceiveData;

    public ClientSocket(DelSocketReceive _CallbackReceiveData)
    {
        CallbackReceiveData = _CallbackReceiveData;

    }

    public void ConnectSocket()
    {

        NetSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        severEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1000);

        byte[] msg = new byte[4];
        NetKind netknd = NetKind.Connect;
        msg[0] = (byte)netknd;

        NetSocket.SendTo(msg, severEndPoint);


        byte[] buffer = new byte[1024];
        NetSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref severEndPoint, CallbackRecieveFrom, buffer);
    }


    private void CallbackRecieveFrom(IAsyncResult result)
    {
        byte[] receiveData = new byte[1024];
        receiveData = (byte[])result.AsyncState;

        if (CallbackReceiveData != null)
            CallbackReceiveData(receiveData);

        byte[] byteData = new byte[1024];
        NetSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref severEndPoint, CallbackRecieveFrom, byteData);
    }



    public void SendPacketData(byte[] data)
    {
        NetSocket.SendTo(data, severEndPoint);
    }
}

 

 

 

- SocketManager 코드

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NetSocketManager : MonoBehaviour
{

    #region sigleton
    private static NetSocketManager _instance;
    public static NetSocketManager Getsingleton
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType(typeof(NetSocketManager)) as NetSocketManager;
                if (_instance == null)
                {
                    _instance = new GameObject("NetSocketManager").AddComponent<NetSocketManager>();
                    DontDestroyOnLoad(_instance.gameObject);
                }
            }
            return _instance;
        }
    }
    #endregion

    private ClientSocket NetSocket;
    public void Init()
    {
        NetSocket = new ClientSocket(RecievedPacketData);
        NetSocket.ConnectSocket();
    }


    Queue<ByteData> Que_Packet = new Queue<ByteData>();
    void RecievedPacketData(byte[] packet)
    {
        ByteData data = new ByteData(packet);
        Que_Packet.Enqueue(data);
    }

    void ProcessReceivedPacket()
    {
        if(Que_Packet.Count > 0)
        {
            ByteData receivedData = Que_Packet.Dequeue();
            NetKind knd = (NetKind)receivedData.Getbyte();
            Debug.Log("ReceivedPacket : " + knd);
            switch (knd)
            {
                case NetKind.Connect:
                    break;
                case NetKind.Disconnect:
                    break;
                case NetKind.Move:
                    Main.Getsingleton.NetReceived_MovePosPlayer(receivedData);
                    break;
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        ProcessReceivedPacket();
    }







    public void SendData(ByteData packet)
    {
        if (NetSocket == null) return;

        NetSocket.SendPacketData(packet.data);
    }


    public void Disconnect()
    {
        ByteData data = new ByteData(2, 0);
        data.InPutByte((byte)NetKind.Disconnect);
        SendData(data);
    }

}

 

 

 

 

- Player Behaviour 코드

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum PlayerKind { Player,Network, }
public class Player : MonoBehaviour
{
    private int DirectionX;
    private int DirectionZ;
    private float speed = 5f;
    private Transform Tr;
    public PlayerKind PlayerKnd = PlayerKind.Player;
    public uint UserId;
    void Start()
    {
       

        UserId = (uint)Random.Range(1, 50000);
    }

    public void InitPlayer(PlayerKind pknd)
    {
        Tr = this.transform;

        PlayerKnd = pknd;

        if(PlayerKnd == PlayerKind.Player)
        {
            CoSendPosPlayer = StartCoroutine(Co_SendPosPlayer());
        }
    }

    // Update is called once per frame
    void Update()
    {

        InputProcess();



    }

    int count = 0;
    void InputProcess()
    {
        if (PlayerKnd == PlayerKind.Network) return;


       

        if (Input.GetKey(KeyCode.A))
        {
            DirectionX = -1;
        }
        else if (Input.GetKeyUp(KeyCode.A))
        {
            DirectionX = 0;

        }

        if (Input.GetKey(KeyCode.D))
        {
            DirectionX = 1;

        }
        else if (Input.GetKeyUp(KeyCode.D))
        {
            DirectionX = 0;

        }

        if (Input.GetKey(KeyCode.S))
        {
            DirectionZ = -1;
        }
        else if (Input.GetKeyUp(KeyCode.S))
        {
            DirectionZ = 0;

        }

        if (Input.GetKey(KeyCode.W))
        {
            DirectionZ = 1;

        }
        else if (Input.GetKeyUp(KeyCode.W))
        {
            DirectionZ = 0;
        }
    }


    private void FixedUpdate()
    {

       

        MovePlayerProcess();

        NetworkMovePlayerProcess();

    }


    void MovePlayerProcess()
    {
        if (PlayerKnd == PlayerKind.Network) return;

        Tr.Translate(new Vector3(DirectionX, 0f, DirectionZ) * speed * Time.deltaTime);
    }


    Coroutine CoSendPosPlayer = null;
    IEnumerator Co_SendPosPlayer()
    {
        yield return new WaitForSeconds(0.1f);

        SendPosPlayerData();

        CoSendPosPlayer = StartCoroutine(Co_SendPosPlayer());
    }

    void SendPosPlayerData()
    {
        ByteData sendData = new ByteData(64,0);

        sendData.InPutByte((byte)NetKind.Move);
        sendData.InPutByte(UserId);
        //현재위치
        sendData.InPutByte(Tr.position);
        //가는방향
        sendData.InPutByte(DirectionX);
        sendData.InPutByte(DirectionZ);

        //속도?

        NetSocketManager.Getsingleton.SendData(sendData);

    }



    Vector3 NetPlayerPos = new Vector3();
    Vector3 NetPlayerDir = new Vector3();
    public void ReceivedMovePlayerData(ByteData data)
    {
        NetPlayerPos = data.GetVector3();
        int dirX = data.Getint();
        int dirZ = data.Getint();
        NetPlayerDir = new Vector3(dirX, 0, dirZ);

        Debug.Log("NetPlayerDir : " + NetPlayerDir + " / " +NetPlayerDir.magnitude);
    }
    public void ForceNetPlayerPos(ByteData data)
    {
        NetPlayerPos = data.GetVector3();
        int dirX = data.Getint();
        int dirZ = data.Getint();
        NetPlayerDir = new Vector3(dirX, 0, dirZ);

        Tr.position = NetPlayerPos;
    }


    void NetworkMovePlayerProcess()
    {
        if (PlayerKnd == PlayerKind.Player) return;

        if (NetPlayerDir.magnitude > 0)
            Tr.position = Tr.position + (NetPlayerDir * speed * Time.deltaTime);
        else
            Tr.position = Vector3.Lerp(Tr.position, NetPlayerPos, Time.deltaTime * 10f);
    }

}

 

 

 

Player.cs
0.00MB
ByteData.cs
0.01MB
ClientSocket.cs
0.00MB
Main.cs
0.00MB
NetSocketManager.cs
0.00MB

 

반응형

+ Recent posts