将流连接到 Java 中的套接字

Connecting the Streams to a Socket in Java

我对编程很陌生,而且作为家庭作业的一部分,我正在做一个聊天应用程序。它应该通过 IP 地址连接到另一台计算机,在单独的线程中创建服务器和套接字,不断地监听和写入发生的事情。这没关系。 `

public class MyConnection extends Thread {
    @Override
    public void run (){

    try (ServerSocket eServer = new ServerSocket(1300);
        Socket cn = eServer.accept();
        BufferedReader bf = new BufferedReader(new InputStreamReader(cn.getInputStream()));)
    {
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = bf.readLine()) != null) {
        sb.append(line);
        }
        HelpClass.writeStatus(sb.toString());
        }

    catch(IOException exc ) {Pomocna.writeStatus("An error occured: " + exc.getMessage());
}
}
}

`

当我想制作发送消息的方法时,问题就出现了,我必须将我的 OutputStream 连接到套接字。由于某种原因,他看不到 Socket。方法 send() 我已经在一个单独的 class 中定义为静态方法,称为 HelpClass(不确定这是否是一个好习惯),方法如下:

`

 public static void send(String content){
    try (BufferedOutputStream bof = new BufferedOutputStream(getOutputStream(cn))){
        byte[] b = content.getBytes(Charset.forName("UTF-8"));
        bof.write(b);
    }

catch(IOException exc) {System.out.println("An error occured: " +     exc.getMessage());}
    }

`

在我没有想法的那一刻,将不胜感激任何帮助。

我建议你传入 Socket cn 来解决这个问题,并明确你发送的是什么。

注意:您应该 - 永远只为每个连接创建一个 BufferedOutputStream 或一个 BufferedInputStream,否则您可能会看到数据丢失。 - 或者不要使用缓冲,因为您似乎根本没有使用它。

也不要捕获异常并继续,就好像它没有发生一样。如果写入失败则需要关闭连接。即不要假设记录它就足够了。完全不抓会更简单

我可能会这样写send

public static void send(Socket sc, String content) throws IOException {
    String toSend = content+"\n"; // assume we are reading with readLine()
    sc.getOutputStream().write(toSend.getBytes(StandardCharSets.UTF8));
}