gpt4 book ai didi

Java TCP 多线程问题

转载 作者:可可西里 更新时间:2023-11-01 02:52:39 36 4
gpt4 key购买 nike

我的程序运行良好,许多用户可以连接并向服务器发送命令。但是,当用户使用命令向服务器发送垃圾邮件时,服务器会阻止所有其他客户端,并且服务器不会接收来自发送垃圾邮件的客户端以外的客户端的消息。这是为什么?

TCP接受连接


    package game.server;

import java.io.IOException;
import java.net.Socket;

public class TCPAcceptConnections implements Runnable
{
public static Socket clientSocket = null;;
int clientID = -1;

public void run()
{
while(Main.TCP)
{
try
{
clientSocket = TCPServer.serverSocket.accept();
System.out.println("Client Connected.");
clientID++;

new TCPClientManager(clientSocket, clientID).run();
}
catch (IOException e)
{
System.out.println("Couldn't create client socket.");
System.exit(-1);
}
}
}
}

TCP客户端管理器:


    package game.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TCPClientManager implements Runnable
{
Socket client;

int clientID;

static PrintWriter out;
static BufferedReader in;
String inputLine, outputLine;

boolean destroy = false;

public TCPClientManager(Socket cs, int id)
{
try
{
client = cs;
clientID = id;
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch(IOException e)
{
e.printStackTrace();
}
}

public void run()
{
System.out.println("Created TCPManager for client.");
String command;

while(!destroy)
{
try
{
if((command = in.readLine()) != null) //If received something
{
System.out.println("Commad received: " + command);
System.out.println(" " + Commands.proccessCommand(command));
System.out.println("Command proccessed");
}
else
{
client.close();
destroy = true;
}
} catch (IOException e)
{
try
{
client.close();
} catch (IOException e1)
{
e1.printStackTrace();
destroy = true;
}
System.out.println("Client lost connection.");
destroy = true;
}
}
System.out.println("TCPManager for client destroyed.");
}
}

命令:


package game.server;

public class Commands
{
public static String proccessCommand(String command)
{
if(command.equalsIgnoreCase("cp"))
{
System.out.println("Creating player...");
System.out.println(" Retrieved client");
return "Player Created";
}
else
{
return "Unkown command: " + command;
}
}
}

最佳答案

如果您收到未知命令,您应该记录它并关闭连接。

但是你有一个更严重的问题。当它读取 null 时,您不会停止客户端处理程序。因此,一旦客户端断开连接,读取将永远无用地旋转。如果 readLine() 返回 null,则必须关闭套接字并退出循环。如果您收到任何 IOException,您还必须关闭套接字。

关于Java TCP 多线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13105488/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com