可以读写消息的Java Chat Server

时间:2017-10-17 13:18:48

标签: java

我尝试创建一个可以向多个客户端发送和接收消息的服务器。但我有问题,客户端甚至没有将消息发送到我希望的服务器。我还没有添加Server的写入部分,我现在只是尝试让Server从客户端读取消息。谢谢你的帮助。这是我的服务器和我的客户:

public class Main {


public static ArrayList<PrintWriter> writers = new ArrayList<PrintWriter>();
public static void main(String[] args) {
    try {
        ServerSocket sock = new ServerSocket(9898);
        while (true) {
            try {
                Socket client = sock.accept();
                PrintWriter writer = new PrintWriter(client.getOutputStream());
                writers.add(writer);
                Thread t = new Thread(new Handler(client));
                t.start();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Server Started");
}

}

public class Handler implements Runnable {
private Socket client;

public Handler(Socket client) {
    this.client = client;
}
@Override
public void run() { 
    try {
        //Streams---------------------------------
        OutputStream out = client.getOutputStream();
        PrintWriter writer = new PrintWriter(out);

        InputStream in = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));  
        //----------------------------------------


        String s = null;
        while(true) {
            if((s=reader.readLine()) != null) {
        }       System.out.println(s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

public class Manager实现了Runnable {

Socket sockel;
String pcname = System.getProperty("user.name");
BufferedReader reader;
PrintWriter writer;
@Override
public void run() {
    try {
        sockel = new Socket("localhost", 9898);
        //Streams
        reader = new BufferedReader(new InputStreamReader(sockel.getInputStream()));
        writer = new PrintWriter(sockel.getOutputStream());
        //--------------
        System.out.println("Connected to: " + sockel.getInetAddress());
        writer.write("hello");
        writer.flush();
        System.out.println("here");
        String command = reader.readLine();
        while(!command.equalsIgnoreCase("close" + pcname)) {
            System.out.println("Got Message: " + command);
        }
    }catch(IOException e) {
        e.printStackTrace();
    }
}

}

1 个答案:

答案 0 :(得分:0)

您没有使用班级经理。 你必须创建两个项目一个客户端和另一个服务器并启动服务器项目,然后启动客户端。

我希望这能帮到你。