简体   繁体   English

将流连接到Java中的套接字

[英]Connecting the Streams to a Socket in Java

I am quite fresh in programming and as a part of homework doing a chat app. 我在编程方面很新鲜,并且作为做聊天应用程序的家庭作业的一部分。 It should connect to another computer via IP address, have created Server and Socket in a separate Thread, constantly listening abd writting what comes. 它应该通过IP地址连接到另一台计算机,并在单独的线程中创建了服务器和套接字,并不断地听着写着什么。 And this is ok. 没关系。 ` `

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());
}
}
}

` `

The problem arises when I want to make method for sending message, where I have to connect my OutputStream to the socket. 当我想制作发送消息的方法时,必须将OutputStream连接到套接字,就会出现问题。 He cannot see the Socket for some reason. 由于某种原因,他看不到套接字。 Method send() I have defined as static i one separate class, called HelpClass (not sure if this is a good practice or not), here is the method: 方法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());}
    }

` `

In the moment I have been out of ideas, would appreciate any help. 目前我已经没有想法了,不胜感激。

I suggest you pass in Socket cn to solve this issue and to make it clear what you are sending. 我建议您传入Socket cn来解决此问题并弄清楚您要发送的内容。

Note: You should either - only create one BufferedOutputStream or one BufferedInputStream per connection ever, or you are likely to see data loss. 注意:您应该-只能为每个连接创建一个BufferedOutputStream或一个BufferedInputStream,否则您可能会看到数据丢失。 - or don't use buffering as you don't appear to be using it anyway. -或不要使用缓冲,因为您似乎根本就没有使用它。

Also don't catch an exception and continue as if it didn't happen. 也不要捕获异常并继续进行,好像没有发生一样。 If you fail to write you need to close the connection. 如果写入失败,则需要关闭连接。 ie don't assume that logging it is enough. 即不要以为日志记录就足够了。 It would be simpler to not catch it at all. 根本不了解它会更简单。

This is how I might write send 这就是我写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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM