Chat.cs
2.2 KB
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
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
public class Chat : MonoBehaviour
{
public TransportTCP m_transport;
public ChatText commentTextPrefab;
public Transform commentHolder;
public string m_hostAddress {get; set;}
private const int m_port = 50763;
private bool m_isServer = false;
// Use this for initialization
void Start()
{
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
System.Net.IPAddress hostAddress = hostEntry.AddressList[0];
Debug.Log(hostEntry.HostName);
m_hostAddress = "127.0.0.1";
m_transport.onStateChanged += OnEventHandling;
}
IEnumerator UpdateChatting()
{
while(true)
{
byte[] buffer = new byte[1400];
int recvSize = m_transport.Receive(ref buffer, buffer.Length);
if (recvSize > 0) {
string message = System.Text.Encoding.UTF8.GetString(buffer);
Debug.Log("Recv data:" + message );
AddComment(message);
}
yield return null;
}
}
void Send(string message)
{
message = "[" + DateTime.Now.ToString("HH:mm:ss") + "] " + message;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message);
m_transport.Send(buffer, buffer.Length);
AddComment(message);
}
void AddComment(string message)
{
var newComment = Instantiate(commentTextPrefab,commentHolder);
newComment.SetUp(message);
}
void OnApplicationQuit() {
if (m_transport != null) {
if(m_isServer)
{
m_transport.StopServer();
}
else
{
m_transport.Disconnect();
}
}
}
public void OnEventHandling(NetEventState state)
{
switch (state.type) {
case NetEventType.Connect:
AddComment("접속");
break;
case NetEventType.Disconnect:
AddComment("접속 종료");
break;
}
}
public void CreateRoom()
{
m_transport.StartServer(m_port, 1);
m_isServer = true;
}
public void JoinChatRoom()
{
bool ret = m_transport.Connect(m_hostAddress, m_port);
if (ret) {
StartCoroutine("UpdateChatting");
}
else {
Debug.LogError("Failed");
}
}
public void Leave()
{
if (m_isServer == true) {
m_transport.StopServer();
}
else {
m_transport.Disconnect();
}
StopCoroutine("UpdateChatting");
}
}