0

我是Java新手,我正在尝试找出一些问题..

我希望能够通过指定他的 ID 从服务器向客户端发送消息。我想了想,我认为如果我为每个连接的客户端创建一个 PrintWriter 并将其放入 PrintWriter 数组中,这将是一个好主意,但这似乎不起作用,希望你们能/会帮助我。

一些方法名称是用我的母语命名的,希望这不是问题。

package homeControl;

import java.net.*;
import java.util.Scanner;
import java.io.*;
import java.awt.*;

public class Server {
    String sporocilo = null;
    int id = 0;
    ServerHandler handler = new ServerHandler();

    public void sprejmiPovezavo() {
        try {
            ServerSocket svrSock = new ServerSocket(5000);
            Socket klientSocket = svrSock.accept();

            new Thread(new ServerHandler(klientSocket));
        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server svr = new Server();
        svr.sprejmiPovezavo();
    }
}

服务器处理程序代码:

package homeControl;

import java.net.*;
import java.io.*;
import java.awt.*;

public class ServerHandler implements Runnable {
Socket klientSocket;
static int userCounter = 0;
static int selectedId = 0;
BufferedReader reader;
PrintWriter writer;
PrintWriter[] writerHolder = new PrintWriter[10];

outputHelper out = new outputHelper();  

public ServerHandler(Socket klientSocket) throws IOException {
    userCounter++;
    this.klientSocket = klientSocket;
    writer = new PrintWriter(this.klientSocket.getOutputStream());
    writerHolder[userCounter] = writer;

    InputStreamReader inReader = new InputStreamReader(this.klientSocket.getInputStream());
    reader = new BufferedReader(inReader);

    out.frameOutput(this.klientSocket.getInetAddress().toString(), "Server sprejel povezavo:");

    selectedId = userCounter;
    posljiSporocilo("wassup");
}

public ServerHandler() {
    // Do not launch the main Constructor
}

public void run(){
    String inMessage = null;
    try{
        while((inMessage = reader.readLine()) != null) {
            System.out.println("Server Sprejel: " + inMessage);
        }
    } catch(IOException ex){
        ex.printStackTrace();
    }   
}

public  void selectId(int id){
    selectedId = id;
}

public void posljiSporocilo(String sporocilo){
    writerHolder[selectedId].println(sporocilo + "\n");
    writerHolder[selectedId].flush();
}
}
4

1 回答 1

0

根据您所写的内容,只有一个客户端能够连接到服务器。以下更改允许您接受多个客户端。服务器接受并提供连接请求,然后继续接受其他请求。

ServerSocket svrSock;
try{
    svrSock = new ServerSocket(5000);
} catch(IOException e){
    e.printStackTrace();
    System.exit(-1);
}
while(true){
   try {
        Socket klientSocket = svrSock.accept();
        new Thread(new ServerHandler(klientSocket));
   } catch(IOException ex) {
        ex.printStackTrace();
   }
}
于 2013-09-19T10:00:38.007 回答