-3
我在JAVA
中獲得了tcp server
,並且在統一腳本中獲得了名爲Client
的類。 Client
是一個singleton
,它連接到服務器的constructor
。當我按下播放按鈕時,它會連接到服務器,但當我再次按下停止遊戲時,客戶端不會自動斷開連接,因此當我再次運行遊戲時,它將獲取堆棧,因爲他嘗試從已連接的計算機進行連接。我試圖在destructor
斷開連接,但它從未被調用過。我該怎麼做?我也試圖實施IDisposable
,但我不知道你是否需要打電話或garbage collector
稱它(對我來說不是)。 這是客戶端的代碼(read
write
和loop
是不是這個問題很重要,但我離開它,以防有人需要它):當完成團結遊戲時調用代碼
using Assets.Scripts.Tools;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
using System;
public class Client : System.Object, IDisposable{
private TcpClient tcp;
private Stream stream;
private IClientCallback callback;
private Thread recvThread;
private static Client instance = null;
public static Client Instance
{
get
{
if (instance == null)
instance = new Client();
return instance;
}
}
private Client()
{
Init();
}
public void Init()
{
Log.D("Init the client");
tcp = new TcpClient();
tcp.Connect(Main.IP, Main.PORT);
stream = tcp.GetStream();
recvThread = new Thread(loop);
recvThread.Start();
}
public void setCallback(IClientCallback callback)
{
this.callback = callback;
}
// recving loop
private void loop()
{
while (true)
{
Message msg = Read();
if (callback != null)
{
callback.Callback(msg);
}
else
{
Log.E("callbackPointer is null, msg not handheld");
}
}
}
public void disconnect()
{
tcp.Close();
stream.Close();
}
// read a message from the server (will wait until a message is recved
private Message Read()
{
try
{
int val;
string res = "";
do
{
val = stream.ReadByte();
res += (char)val;
} while (val != Code.END_MESSAGE && val != -1);
return new Message(res);
}
catch (IOException)
{
Log.E("Could not read from the server, disconnecting");
throw new System.Exception("could not read from the server");
}
}
// Write a message to the server
public void Write(Message msg)
{
try
{
Log.D("Write:", msg.getDebug());
stream.Write(msg.getBytes(), 0, msg.getBytes().Length);
stream.Flush();
}
catch (IOException)
{
Log.E("Could not send message to the client");
throw new System.Exception("could not write to the server: " + msg.getCode().ToString() + msg.toString());
}
}
public void Dispose()
{
Log.D("never been called");
}
~Client()
{
Log.D("never been called");
}
}
請問您可以發佈您的代碼嗎? –
@MichaelMeyer我編輯我的問題 – Roni
也許這有幫助嗎? https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationQuit.html https://docs.unity3d.com/ScriptReference/EditorApplication-playmodeStateChanged.html – yes