[英]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.