如何启动两个客户端,只有两个客户端之间聊天,使用小程序和servlet? [英] How to initiate chatting between two clients and two clients only, using applets and servlets?

查看:122
本文介绍了如何启动两个客户端,只有两个客户端之间聊天,使用小程序和servlet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先需要为我的前面的问题道歉。 (您可以检查我的个人资料为他们)他们似乎比要求给予解答更多的问题。于是,我放下了所有开始他们荒谬的问题的实际问题。

我想设计一个聊天小程序。截至目前,我有codeD上的小程序和servlet的的小程序,servlet和沟通。在servlet侧的code是这样的,我是能够建立使用小程序客户端之间的聊天,但code更像是一个广播的所有功能,即所有客户端将互相聊天。这是我的第一个目标,当我开始设计聊天小程序。第二步是只有两个特定用户之间聊天,就像我们有任何其它的聊天应用程序。所以这是我的主意吧:


  1. 我创建具有广播所有的'code的servlet实例。

  2. 我那么这个实例的地址传递给各自的客户。

  3. 2的客户端小程序使用的地址,然后聊天。技术上,code为'广播所有,但由于只有2个客户端连接到它,它提供了两个客户端之间的聊天功能。因此,2客户端的组具有相同的servlet的不同实例,每个实例句柄在最大两个客户端之间的聊天。

不过,正如predicted,这个想法没有实现!

我试过的创建Servlet实例的使用,但在servlet的一侧发起的会话的,唯一的解决办法是,我不知道如何使用这个会话以后的通信。


  

我现在知道如何使用request.getSession()。所以我设置会话在其param标签的小程序,并使用它与servlet的进一步沟通。但我怎么用这个数据来建立两个客户端之间聊天?正如我前面写的,我有code为broadcast_all聊天如下:


 公共类CustomerServlet延伸的HttpServlet {公共字符串getNextMessage(){
    //创建一个消息接收器,以等待来自新的消息
    //消息源。
    返回新MessageSink()getNextMessage(源)。
}@覆盖
保护无效的doGet(HttpServletRequest的请求,HttpServletResponse的响应)
抛出了ServletException,IOException异常{
    ObjectOutputStream的DOUT =新的ObjectOutputStream(response.getOutputStream());
    串recMSG = getNextMessage();
    dout.writeObject(recMSG);
    dout.flush();
}公共无效broadcastMessage(字符串消息){
    //通过给发送消息到所有的HTTP连接的客户端
    //消息到消息源
    source.sendMessage(消息);
}@覆盖
保护无效的doPost(HttpServletRequest的请求,HttpServletResponse的响应)
抛出了ServletException,IOException异常{
    尝试{
        ObjectInputStream的喧嚣=新的ObjectInputStream(request.getInputStream());
        字符串消息=(字符串)din.readObject();
        ObjectOutputStream的DOUT =新的ObjectOutputStream(response.getOutputStream());
        dout.writeObject(1);
        dout.flush();
        如果(消息!= NULL){
            broadcastMessage(消息);
        }
        //设置状态code,表示不会有任何反应
        response.setStatus(response.SC_NO_CONTENT);
    }赶上(例外五){
        e.printStackTrace();
    }
}
MessageSource的源=新的MessageSource();
}一流的MessageSource扩展观测{
公共无效的sendMessage(字符串消息){
    setChanged();
    notifyObservers(消息);
}
}
类MessageSink实现观测{
字符串消息= NULL; //按更新()设置和读取由getNextMessage()
//通过消息源调用时,它得到一个新的消息
同步公共无效更新(可观察到0,对象ARG){
    //获取新信息
    消息=(字符串)ARG;
    //唤醒了我们等待的线程
    通知();
}
//获取从消息源发出的下一条消息
同步公共字符串getNextMessage(源的MessageSource){
    //告诉我们的源要被告知新邮件
    source.addObserver(本);
    //等到我们的update()方法接收一个消息
    而(消息== NULL){
        尝试{
            等待();
        }赶上(例外五){
            的System.out.println(异常已发生ERR ERR ERR!);
        }
    }
    //告诉源头上阻止告诉我们关于新邮件
    source.deleteObserver(本);
    //现在我们返回收到消息
    //但是首先设置消息实例变量设置为null
    //所以更新()和getNextMessage()可以再次调用。
    字符串messageCopy =消息;
    消息= NULL;
    返回messageCopy;
}
}


  

在该applet的一面,我有一个线程将连接到上面的servlet的使用GET方法来获取新的消息。它使用whil​​e循环,并阻塞,直到它得到从servlet的消息。主线程使用,只要客户端已进入消息POST方法的servlet通信。目前,所有的客户与大家聊天。我想使用上述(或者如果可能的任何其他方式)中使用的相同的方法,以建立两个客户端和仅仅两个客户端之间聊天。我可能有另一个线程的小程序来检查是否有其他用户需要与它交谈,然后交换一些数据,以便只有这两个用户聊天......


然后我试图修改我的广播所有code。在code,我使用实施观察和可观察接口的类。所以,我得到了下一个想法是:


  1. 创建可观察类的新对象(比如class_1)。这个对象是共同的2客户端。

  2. 2的客户,想聊天将使用class_1的同一个对象。

  3. 2的其他客户端将使用class_1不同的对象。

但这里的问题在于实现Observer接口的类(比如class_2)。因为这有观察家监测相同类型的类,即class_1,我怎么建立一个观察员监督class_1的一个对象,另一名观察员监督同级class_1的另一个对象(因为notifyObservers()将通知所有的观察者,我可以' ŧ分配一个特定的观测到一个特定的对象)?

我第一次决定让个别问题,比如如何创建的servlet实例,使用可观察和观察员等在计算器的对象......但我得到了更多的困惑。谁能给我一个想法,如何建立只有两个客户端之间聊天?(我使用HTTP和没有插座或RMI)。

问候,
大额牛。

P.S。感谢所有谁回答我的previous(荒诞)查询。我应该说明的目的早些时候,这样你们可以帮助我更好。


解决方案

您需要所有连接的用户存储在地图<弦乐,使用者> 使用应用程序范围的ServletContext#的setAttribute()。在字符串表示唯一用户标识符(聊天昵称?)。你需要存储的特定的聊天用户,以及在会议范围使用的HttpSession#的setAttribute()。您还需要保存的其他的用户个人聊天在地图<弦乐,使用者> 会议范围的有问题的用户。您可以获得由的getAttribute()法的属性。

这样,你知道哪些用户都可用,哪些用户在当前会话与它是单独聊天的用户。

I first need to apologize for my earlier questions. (You can check my profile for them)They seemed to ask more questions than give answers. Hence, I am laying down the actual question that started all them absurd questions.

I am trying to design a chat applet. Till now, I have coded the applet, servlet and communication between the applet and the servlet. The code in the servlet side is such that I was able to establish chatting between clients using the applets, but the code was more like a broadcast all feature, i.e. all clients would be chatting with each other. That was my first objective when I started designing the chat applet. The second step is chatting between only two specific users, much like any other chat application we have. So this was my idea for it:

  1. I create an instance of the servlet that has the 'broadcast-all' code.
  2. I then pass the address of this instance to the respective clients.
  3. 2 client applets use the address to then chat. Technically the code is 'broadcast-all', but since only 2 clients are connected to it, it gives the chatting between two clients feature. Thus, groups of 2 clients have different instances of the same servlet, and each instance handles chatting between two clients at a max.

However, as predicted, the idea didn't materialize!

I tried to create an instance of the servlet but the only solution for that was using sessions on the servlet side, and I don't know how to use this session for later communications.

I now know how to use the request.getSession(). So I set the session for an applet in its param tag and use it for further communications with the servlet. But how do I use this data to establish chatting between two clients? As I wrote earlier, I have the code for broadcast_all chatting as follows:

public class CustomerServlet extends HttpServlet {

public String getNextMessage() {
    // Create a message sink to wait for a new message from the
    // message source.
    return new MessageSink().getNextMessage(source);
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    ObjectOutputStream dout = new ObjectOutputStream(response.getOutputStream());
    String recMSG = getNextMessage();
    dout.writeObject(recMSG);
    dout.flush();
}

public void broadcastMessage(String message) {
    // Send the message to all the HTTP-connected clients by giving the
    // message to the message source
    source.sendMessage(message);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    try {
        ObjectInputStream din= new ObjectInputStream(request.getInputStream());
        String message = (String)din.readObject();
        ObjectOutputStream dout = new ObjectOutputStream(response.getOutputStream());
        dout.writeObject("1");
        dout.flush();
        if (message != null) {
            broadcastMessage(message);
        }
        // Set the status code to indicate there will be no response
        response.setStatus(response.SC_NO_CONTENT);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
MessageSource source = new MessageSource();
}

class MessageSource extends Observable {
public void sendMessage(String message) {
    setChanged();
    notifyObservers(message);
}
}
class MessageSink implements Observer {
String message = null;  // set by update() and read by getNextMessage()
// Called by the message source when it gets a new message
synchronized public void update(Observable o, Object arg) {
    // Get the new message
    message = (String)arg;
    // Wake up our waiting thread
    notify();
}
// Gets the next message sent out from the message source
synchronized public String getNextMessage(MessageSource source) {
    // Tell source we want to be told about new messages
    source.addObserver(this);
    // Wait until our update() method receives a message
    while (message == null) {
        try {
            wait();
        } catch (Exception e) {
            System.out.println("Exception has occured! ERR ERR ERR");
        }
    }
    // Tell source to stop telling us about new messages
    source.deleteObserver(this);
    // Now return the message we received
    // But first set the message instance variable to null
    // so update() and getNextMessage() can be called again.
    String messageCopy = message;
    message = null;
    return messageCopy;
}
}

On the applet side, I have a thread that will connect to the servlet above using GET method to get new messages. It uses a while loop, and blocks until it gets a message from the servlet. The main thread communicates with the servlet using POST method whenever the client has entered the message. Currently all clients chat with everyone. I want to use the same methods used above (or if possible any other way) to establish chatting between two clients and two clients only. I could possibly have another thread in the applet to check if any other user wishes to chat with it and then exchange some data so that only those two user chat...

I then tried to modify my broadcast-all code. In that code, I was using classes that implemented Observer and Observable interfaces. So the next idea that I got was:

  1. Create a new object of the Observable class(say class_1). This object be common to 2 clients.
  2. 2 clients that wish to chat will use same object of the class_1.
  3. 2 other clients will use a different object of class_1.

But the problem here lies with the class that implements the Observer interface(say class_2). Since this has observers monitoring the same type of class, namely class_1, how do I establish an observer monitoring one object of class_1 and another observer monitoring another object of the same class class_1 (Because notifyObservers() would notify all the observers and I can't assign a particular observer to a particular object)?

I first decided to ask individual problems, like how to create instances of servlets, using objects of observable and observer and so on in stackoverflow... but I got confused even more. Can anyone give me an idea how to establish chatting between two clients only?(I am using Http and not sockets or RMI).

Regards, Mithun.

P.S. Thanks to all who replied to my previous (absurd) queries. I should have stated the purpose earlier so that you guys could help me better.

解决方案

You need to store all connected users in a Map<String, User> in the application scope using ServletContext#setAttribute(). The String denotes the unique user identifier (chat nickname?). You need to store the specific chat User as well in the session scope using HttpSession#setAttribute(). You also need to store the other user in individual chats in a Map<String, User> in the session scope of the users in question. You can obtain the attribute by the getAttribute() method.

This way you know which users are all available and which user is in the current session and with which users it is individually chatting.

这篇关于如何启动两个客户端,只有两个客户端之间聊天,使用小程序和servlet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆