[英]Java ServerSocket.accept(); makes Server or UnityScript Client crash
我正在使用Java服務器和Unity(Javascript / Unityscript)客戶端制作MMORPG。 在服務器端,我有以下內容:
while(running){
System.out.println("Waiting for new client to connect.");
Socket socket = serverSocket.accept(); /*When another client tries to connect,
server stops at this line, "Client connected." is never printed.*/
System.out.println("Client connected.");
if(!running){
System.out.println("Closing server..");
}
ClientListener listener = new ClientListener(socket);
clients.add(listener);
listener.start();
}
因此,當我第一次運行服務器和客戶端時,一切正常。 當我關閉客戶端並嘗試再次運行客戶端時,服務器在serverSocket.accept()處停止; 。 這意味着任一服務器不能使用另一個客戶端,或者客戶端無法連接到服務器。 我認為它是在服務器端,但是我真的不知道是什么原因造成的。
private function ThreadListener(){
client = new TcpClient();
var port = 16304;
try{
print("running..");
client.Connect(IPEndPoint(IPAddress.Parse("127.0.0.1"), port));
ns = client.GetStream();
var data = new byte[1024];
var waitCounter = 0;
print("connection made");
var read = 0;
while(true){
if(ns.CanRead){
read = ns.Read(data, 0, data.Length);
var word = System.Text.Encoding.ASCII.GetString(data, 0, read);
Action(word);
}
}
}
catch (InvOpEx : InvalidOperationException) {
Debug.Log("TCP exception: " + InvOpEx.Message);
}
catch (SockEx : SocketException) {
Debug.Log("Socket exception: " + SockEx.Message);
}
finally {
if(ns != null)
ns.Close();
client.Close();
}
}
注意! 我知道這個統一的客戶端編碼很差,而javascript不是我的強項。 但是,一旦我開始使用它,我將把更多的精力放在提高它的效率和功能上。
編輯1 :客戶端只是凍結,直到我關閉服務器,然后在關閉服務器幾秒鍾后,客戶端給出一條錯誤消息,告知它無法連接到服務器。
編輯2 :我使用Java做了一個測試客戶端,以確保問題不在服務器端。 而且我能夠使用該測試客戶端成功多次連接到服務器。 我認為在自己的論壇上獲得與團結相關的東西的幫助會更容易,因此我將在此提出這個問題。 :)
問題出在客戶端(Javascript)上,當關閉客戶端時,我忘記了關閉ThreadListener()線程。 所以我做了以下功能:
function OnApplicationQuit(){ //this is called before program is closed
running = false;
WorkerThread.Abort();
if(ns != null){
ns.Close();
}
client.Close();
WorkerThread.Join();
WorkerThread = null;
}
現在它可以正常工作了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.