【问题标题】:Connecting the Streams to a Socket in Java在 Java 中将流连接到套接字
【发布时间】:2015-08-29 08:47:12
【问题描述】:

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

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 连接到套接字。由于某种原因,他看不到插槽。方法 send() 我已经定义为静态我一个单独的类,称为 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());}
    }

`

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

【问题讨论】:

    标签: java sockets server inputstream outputstream


    【解决方案1】:

    我建议你通过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));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      • 2013-02-02
      相关资源
      最近更新 更多