socket.io with unity

Unity3D 2018. 12. 24. 18:54
반응형

socketio_unity.unitypackage





서버 코드 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
 
app.get('/', (req, res)=>{
  res.sendFile(__dirname + '/index.html');
});
 
server.listen(3000, ()=>{
  console.log('Socket IO server listening on port 3000');
});
 
// connection event handler
// connection이 수립되면 event handler function의 인자로 socket이 들어온다
io.on('connect'function(socket) {
  
 
  // 접속한 클라이언트의 정보가 수신되면
  socket.on('login'function(data) {
    console.log('Client logged-in:\n name:' + data.name + '\n userid: ' + data.userid);
 
    //console.log(data);
 
    // // socket에 클라이언트 정보를 저장한다
    socket.name = data.name;
    socket.userid = data.userid;
 
    // // 접속된 모든 클라이언트에게 메시지를 전송한다
    io.emit('login', data.name );
    //socket.broadcast.emit('login', data.name);
  });
 
  socket.on("move_friend", (data)=>{
    console.log('Message from %s, %s, %s', data.x, data.y, data.z);
    socket.broadcast.emit('move_friend', data);
  });
 
  // 클라이언트로부터의 메시지가 수신되면
  socket.on('chat'function(data) {
    console.log('Message from %s: %s', socket.name, data.msg);
 
    var msg = {
      from: {
        name: socket.name,
        userid: socket.userid
      },
      msg: data.msg
    };
 
    // 메시지를 전송한 클라이언트를 제외한 모든 클라이언트에게 메시지를 전송한다
    socket.broadcast.emit('chat', msg);
 
    // 메시지를 전송한 클라이언트에게만 메시지를 전송한다
    // socket.emit('s2c chat', msg);
 
    // 접속된 모든 클라이언트에게 메시지를 전송한다
    // io.emit('s2c chat', msg);
 
    // 특정 클라이언트에게만 메시지를 전송한다
    // io.to(id).emit('s2c chat', data);
  });
 
  // force client disconnect from server
  socket.on('forceDisconnect'function() {
    socket.disconnect();
  })
 
  socket.on('disconnect'function() {
    console.log('user disconnected: ' + socket.name);
    socket.broadcast.emit('disconnect', socket.name);
  });
});
cs






클라 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Sample;
 
public class Main : MonoBehaviour {
 
    public Hero hero;
    public Namespace gameLauncher;
 
    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonUp(0))
        {
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, 1000f))
            {
                if (hit.collider.tag == "ground") {
                    hero.Move(hit.point);
                    gameLauncher.Send(hit.point);
                }
            }
        }
        
    }
}
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Hero : MonoBehaviour {
 
    private Animation anim;
    public GameObject model;
    // Use this for initialization
    void Start () {
        this.anim = this.model.GetComponent<Animation>();    
    }
    
    // Update is called once per frame
    void Update () {
        
    }
 
    public void Move(Vector3 tPos)
    {
        if (this.routine != null)
            StopCoroutine(routine);
        this.routine = StartCoroutine(this.MoveImpl(tPos));
    }
 
    private Coroutine routine;
 
    private IEnumerator MoveImpl(Vector3 tPos)
    {
        this.anim.Play("run@loop");
        this.transform.LookAt(tPos);
 
        while (true)
        {
            var dis = Vector3.Distance(tPos, this.transform.position);
            var dir = (tPos - this.transform.position).normalized;
            if (dis <= 0.2f)
            {
                break;
            }
            this.transform.position += 2 * Time.deltaTime * dir;
            yield return null;
        }
        Debug.LogFormat("move complete!");
        this.anim.Play("idle@loop");
    }
}
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
using UnityEngine;
using UnityEngine.UI;
using socket.io;
using Newtonsoft.Json;
 
namespace Sample
{
 
    /// <summary>
    /// The sample show how to restrict yourself a namespace
    /// </summary>
    public class Namespace : MonoBehaviour
    {
 
        public class res_login
        {
            public string name;
        }
 
        public class login
        {
            public string name;
            public string userid;
            public login(string name, string userid)
            {
                this.name = name;
                this.userid = userid;
            }
        }
 
        public class chat
        {
            public login from;
            public string msg;
 
            public chat(login from, string msg)
            {
                this.from = from;
                this.msg = msg;
            }
        }
 
        public class move_friend
        {
            public float x;
            public float y;
            public float z;
            public move_friend(float x, float y, float z)
            {
                this.x = x;
                this.y = y;
                this.z = z;
            }
 
        }
 
        public string userName;
        public string userId;
 
        public InputField inputField;
        public Button btnSend;
 
        private GameObject HeroPrefab;
        private Hero friend;
        private Socket socket;
 
        private void Awake()
        {
            this.HeroPrefab = Resources.Load<GameObject>("HeroPrefab");
        }
 
        public void Send(Vector3 tPos)
        {
            var data = JsonConvert.SerializeObject(new move_friend(tPos.x, tPos.y, tPos.z));
            socket.EmitJson("move_friend", data);
 
            //if (this.friend != null)
            //    this.friend.Move(tPos);
        }
 
        void Start()
        {
 
            Application.runInBackground = true;
 
            var serverUrl = "http://localhost:3000";
 
            // news namespace
            //var news = Socket.Connect(serverUrl + "/news");
            //news.On(SystemEvents.connect, () => {
            //    news.Emit("woot");
            //});
            //news.On("a message", (string data) => {
            //    Debug.Log("news => " + data);
            //});
            //news.On("item", (string data) => {
            //    Debug.Log(data);
            //});
 
            //// chat namespace
            this.socket = Socket.Connect(serverUrl);
            socket.On("connect", () =>
            {
                var data = JsonConvert.SerializeObject(new login(this.userName, this.userId));
                Debug.LogFormat("data: {0}", data);
                socket.EmitJson("login", data);
 
            });
 
            socket.On("login", (string data) => {
 
                Debug.Log(data);
 
                
 
 
                //if (aa.name != this.userName)
                //{
 
                //}
                this.friend = Instantiate(this.HeroPrefab).GetComponent<Hero>();
                this.friend.transform.position = Vector3.zero;
 
            });
 
            socket.On("move_friend", (string data) => {
                Vector3 tPos = JsonConvert.DeserializeObject<Vector3>(data);
 
                if (this.friend != null)
                    this.friend.Move(tPos);
            });
 
            socket.On("chat", (string data) => {
                Debug.LogFormat("data: {0}", data);
            });
 
            socket.On(SystemEvents.disconnect, () => {
                Debug.LogFormat("disconnect");
                GameObject.Destroy(this.friend.gameObject);
            });
 
 
 
            this.btnSend.onClick.AddListener(() =>
            {
 
                Debug.LogFormat("{0}", inputField.text);
                var chat = JsonConvert.SerializeObject(new chat(new login(this.userName, this.userId), inputField.text));
                socket.EmitJson("chat", chat);
            });
        }
 
    }
 
}
cs





참고: 

https://meetup.toast.com/posts/112


https://github.com/nhnent/socket.io-client-unity3d


https://code.visualstudio.com/docs/nodejs/nodejs-tutorial


https://assetstore.unity.com/packages/tools/network/socket-io-for-unity-21721


https://poiemaweb.com/nodejs-socketio


https://github.com/nhnent/socket.io-client-unity3d/wiki/Sample



반응형

'Unity3D' 카테고리의 다른 글

nodejs restful api unity  (0) 2018.12.31
Unity에서 .NET 4.x 사용  (0) 2018.12.27
GPGS 클라우드 저장/불러오기  (0) 2018.12.03
GPGS 리더보드  (0) 2018.11.29
GPGS 업적  (0) 2018.11.28
: