-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetTest.cs
More file actions
156 lines (140 loc) · 3.33 KB
/
Copy pathNetTest.cs
File metadata and controls
156 lines (140 loc) · 3.33 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
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
156
/*
*┌──────────────────────────────────┐
*│ Copyright(C) 2016 by Antiphon.All rights reserved. │
*│ Author:by Locke Xie 2017-01-03 │
*└──────────────────────────────────┘
*
* 功 能:
* 类 名: NetTest.cs
*
* 修改历史:
*
*
*/
using UnityEngine;
using UnityEngine.UI;
using System.Threading;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class NetTest: MonoBehaviour,INetworkCop
{
public string IP = "127.0.0.1";
public int Prot = 6650;
public bool isJava;
public InputField input;
public InputField read;
public Thread thread;
NetworkSys network;
int status;
public string msg = "";
public byte[] msgB;
string msgbuff = "";
bool isReceive = false;
bool isConect = false;
bool connect;
void Awake()
{
network = new NetworkSys(this, IP, Prot);
network.isJavaServer = isJava;
thread = new Thread(new ThreadStart(network.Connect));
}
void OnGUI()
{
if(GUILayout.Button("连接"))
{
Connect();
}
if(GUILayout.Button("断开连接"))
{
Stop();
}
if(isReceive)
{
isReceive = false;
msgbuff = msg;
read.text +="Server: "+ msg + "\n";
Debug.Log("已收到服务器消息:" + "<color=green>" + msg + "</color>");
}
if(connect && isConect != network.socket.Connected)
{
isConect = network.socket.Connected;
Debug.Log(isConect);
}
}
void OnDisable()
{
Stop();
}
public void SendMsg()
{
SendMsg(input.text);
Debug.Log("已发送:"+input.text);
input.text = "";
}
public void Connect()
{
connect = true;
if(thread == null)
{
network = new NetworkSys(this, IP, Prot);
thread = new Thread(new ThreadStart(network.Connect));
}
if(!thread.IsAlive)
{
try
{
thread.Start();
} catch(Exception e)
{
Debug.Log(e);
}
}
}
public void Stop()
{
connect = false;
if(!network.isDispose)
{
network.Close("手动断开连接");
}
if(thread != null)
{
thread.Abort();
thread = null;
}
}
public void ReadMsg(Message msg)
{
isReceive = true;
this.msgB = msg.BMsg;
this.msg = msg.SMsg;
}
public int SendMsg(string msg)
{
return network.SendMsg(new Message(msg));
}
public void ErrorInfo(string msg)
{
Debug.Log("Error:" + "<color=red>" + msg + "</color>");
//StartCoroutine(WaitReConnect());
}
IEnumerator WaitReConnect()
{
int i = 0;
while(thread != null)
{
yield return new WaitForSeconds(0.02f);
++i;
if(i > 100)
{
break;
}
}
Connect();
}
public void SuccessInfo()
{
}
}