我正在用Java对服务器进行编程,该服务器每秒向客户端广播Date()函数。问题在于它仅适用于一个客户端,但是当我开始对多客户端支持进行修改时,它仅广播Date()一次,然后停止,就像该函数仅被调用一次一样。我找不到我在做什么错,所以我只粘贴代码,希望有人会发现错误。我在网上搜索,但最终比开始时更加困惑。对于客户端程序,我使用Windows的Tellnet终端应用程序。
public class Server
{
private ServerSocket SERVER;
private int PORT;
private Socket CLIENT;
public Server()
{
PORT = 8818;
try
{
SERVER = new ServerSocket(PORT);
System.out.println("Server started on port: " + PORT);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
public void On() throws IOException
{
while(true)
{
CLIENT = SERVER.accept();
new ClientHandler(CLIENT).start();
}
}
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class ClientHandler extends Thread
{
private Socket CLIENT;
private OutputStream out;
public ClientHandler(Socket CLIENT)
{
System.out.println("Accepted Connection from: " + CLIENT.getInetAddress());
this.CLIENT = CLIENT;
}
public void run()
{
try
{
out = CLIENT.getOutputStream();
out.write(("Time now is: " + new Date() + "\n").getBytes());
sleep(1000);
}
catch(Exception e)
{
System.out.println(CLIENT.getInetAddress() + " has left the session");
try
{
out.close();
CLIENT.close();
}
catch(IOException j)
{
System.out.println("Unexpected Error");
System.exit(-1);
}
}
}
}
最佳答案
您的修改几乎奏效了-以下是一个正在运行的版本,仅对您的代码进行了少量修改。
在修改的一部分中,您无意中删除了run函数中的while循环,这意味着Date()函数实际上仅被调用了一次。为此,请删除run()中的while循环,并在打印日期(在telnet窗口中)后显示消息“使用run函数完成”。打印。
我向每个带有日期的客户端添加了一个标识符。静态cnt类字段可确保每个客户端具有不同的ID。
我使用以下命令在单独的命令提示符终端中启动了单独的客户端telnet localhost 8818
,以便它们同时运行。底部是第三个客户端的输出。
我确实将代码切换为camelCase约定(以小写字母开头的变量,并为每个新单词大写),因为所有CAPS通常都保留用于常量,并且更改使代码对我来说更容易阅读。
public class Server
{
private ServerSocket server;
private int port;
private Socket client;
public Server()
{
port = 8818;
try
{
server = new ServerSocket(port);
System.out.println("Server started on port: " + port);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
public void on() throws IOException
{
while(true)
{
client = server.accept();
new ClientHandler(client).start();
}
}
}
public class ClientHandler extends Thread {
private Socket client;
private OutputStream out;
private int id;
private static int cnt=0;
public ClientHandler(Socket client) {
System.out.println("Accepted Connection from: " + client.getInetAddress());
this.client = client;
id=cnt;
cnt++;
}
public void run() {
try {
out = client.getOutputStream();
while (true) {
out.write(("Client " + id + ": Time now is: " + new Date() + "\n").getBytes());
sleep(1000);
}
} catch (Exception e) {
System.out.println(client.getInetAddress() + " has left the session");
try {
out.close();
client.close();
} catch (IOException j) {
System.out.println("Unexpected Error");
System.exit(-1);
}
}
System.out.println("Done with the run function.");
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Server s = new Server();
s.on();
}
}
关于java - Java中的多客户端服务器,也许线程无法正常运行,或者我不知道,无法找出原因,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56653688/