从服务器接收消息

时间:2018-05-03 07:58:27

标签: java network-programming chat serversocket

我正在像项目这样的聊天室工作,我正试图弄清楚如何在聊天室发送消息时从聊天室的其他用户那里接收消息。 这就是我做的事情

class ListenFromServer extends Thread {

    public void run() {
        while(true) {
            try {
                 Console(bin.readLine());
            }
            catch(IOException e) {
                Console("Server has closed the connection: ");
                break;
            }
        }
    }
}

bin

InputStream in = s.getInputStream();
bin = new BufferedReader(new InputStreamReader(in));

,控制台只是将消息附加到聊天JTextArea

这段代码的唯一问题是我的程序只是卡在了,并且没有做任何其他事情,尽管它在一个线程中。

2 个答案:

答案 0 :(得分:0)

当对等方关闭连接时,

BufferedReader.readLine()不会抛出IOException。它返回null,你需要测试它。

  

这段代码唯一的问题是我的程序只是卡在[read loop]

因为您忽略了EOS条件。

  

并没有做任何其他事情,尽管它在线程中。

不相关。

答案 1 :(得分:-1)

我想您需要设置一个数据库,您希望在更新所述客户端时注册从客户端发送的每条消息,以确保它们将最后的消息添加到数据库中。

您将需要JSON,因为它可能是在服务器和客户端之间交换信息的最佳方式,这里有一些您应该看看来处理JSON解析部分的函数。

What is a JSON object : (just to be clear) A .json file contains text-based representations of data structures and objects. A JSON object is delimited by "{" and "}" and represent a single object/structure inside a .json file.

JSONObject : It's a type representing a single JSON object in JAVA.

JSONArray : Seems obvious, but it's an array wich contains JSONObject elements, 
                i recommend you to use this to keep your objects packed into an array,
                this type is providing a lot of usefull methods aswell as JSONObject does,
                i'll list some of them below it's up to you to search for the others. 

JSONArray.getJSONObject(index) : Pass it an index and it will return the JSONObject stored 
                                     at this index.
JSONArray.put([value] | [index, value]) : This might be extremly straightforward but it's actually pretty 
                           usefull if you want to build a JSONArray, pass it a JSONObject 
                           or another common type (int, String, etc) and it will add it to 
                           your JSONArray. 
                           Depending on what you pass it you'll need an index aswell.

JSONObject.keys() : Returns an iterator of the String names in your JSONObject.

JSONObject.put(name, value) : Create a field in your JSONObject using the name you passed 
                                  and assigning the value to it.

JSONObject.getString(name) : Pass the name of a field to it and it will return 
 it's value as a String. As you may have guess already, there is a couple of those, not only getString().

对于数据库连接和交互部分,它可能会有所不同,具体取决于您选择使用的内容以及您选择的方式(您可以使用HttpClient Java class直接访问数据库及其数据或使用HTTP调用以与使用API​​相同的方式恢复数据),有很多教程,我会用一些链接更新它(目前不能记住它们)。

希望这有助于指导您自己的研究。 其余的由你决定。