我有一个
tcp server
JAVA
还有一个叫做
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");
}
}