Home » Java » websocket – Why Java session.getBasicRemote().sendText() not working, but has no error message?-Exceptionshub

websocket – Why Java session.getBasicRemote().sendText() not working, but has no error message?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m following the WebSocket Java examples on this page : https://www.developer.com/java/ent/developing-websocket-clientserver-endpoints.html

My Code looks like this :

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Date;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/echo")
public class EchoWebSocket
{
    boolean showTime_B=false;

    @OnOpen
    public void onOpen(Session session)
    {
        System.out.println("onOpen::" + session.getId());
    }

    @OnClose
    public void onClose(Session session)
    {
        System.out.println("onClose::" + session.getId());
    }

    @OnMessage
    public void onMessage(String message,Session session)
    {
        System.out.println("onMessage[String]::From=" + session.getId());

        try
        {
            session.getBasicRemote().sendText(message.toUpperCase()+(showTime_B?"  [ "+new Date()+" ]":""));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @OnMessage
  public void onMessage(ByteBuffer byteBuffer,Session session)
    {
        System.out.println("onMessage[byteBuffer]::From=" + session.getId());

        try
        {
            session.getBasicRemote().sendText(Arrays.toString(byteBuffer.array())+(showTime_B?"  [ "+new Date()+" ]":""));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Throwable t)
    {
        System.out.println("onError::" + t.getMessage());
    }
}

// =======================================================================

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.net.URI;
import javax.swing.JTextArea;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class TestWebsocketClient
{
    private String uri =    "ws://localhost:8080/WebsocketTest/testserver";
    JTextArea messageTextArea;
  private Session session;

    public TestWebsocketClient(String uri,JTextArea messageTextArea)
    {
        this.uri=uri;
        this.messageTextArea=messageTextArea;
        try
        {
            System.out.println(" TestWebsocketClient[uri] : "+uri);
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(this,new URI(uri));
        }
        catch (Exception e)
        {
      e.printStackTrace();
        }
    }

    @OnOpen
    public void onOpen(Session session)
    {
        this.session = session;
    }

    @OnMessage
    public void onMessage(String msg,Session session)
    {
        this.session = session;
//      messageTextArea.append(msg+" ?\n");

        GsonBuilder builder = new GsonBuilder(); 
//        builder.setPrettyPrinting(); 

        Gson gson = builder.create();
        Message message = gson.fromJson(msg,Message.class);
//  System.out.println(message);
//  msg = gson.toJson(message); 
//  System.out.println(msg);  

//  messageTextArea.append(msg+"# \n"); 
        messageTextArea.append(message.getFrom() + " : " + message.getContent() + " # \n");
    }

    public void sendMessage(String message)
    {
        try
        {
            System.out.println(" TestWebsocketClient.sendMessage[ "+message+" ]  uri = "+uri);
            System.out.println(session.getBasicRemote());   // Wrapped: Basic
            session.getBasicRemote().sendText(message);     // [ Not sending message, and no error ?! ]
        }
        catch (IOException e)
        {
      e.printStackTrace();
        }
    }
}

// =======================================================================

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URI;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
public class WebSocket_Panel extends JPanel implements Runnable
{
public static final long serialVersionUID=26362862L;
static Dimension Screen_Size=Toolkit.getDefaultToolkit().getScreenSize();
int W=800,H=600;
JLabel timeLabel=new JLabel("Time");
JButton phoneNumberButton=new JButton("Phone Number");
Insets An_Inset=new Insets(0,0,0,0);
JTextArea messageTextArea = new JTextArea();
String chatUri = "ws://localhost:8080/Dir_WebSocket_Chat_And_Whiteboard/chat/";
WebSocketClient chatClient = new WebSocketClient();
ChatSocket chatSocket = new ChatSocket(messageTextArea);
URI chatURI;
ClientUpgradeRequest chatRequest;
TestWebsocketClient testWebsocketClient;
Thread WebSocket_Panel_Thread;
public WebSocket_Panel()
{
JLabel space_1_Label = new JLabel();
space_1_Label.setPreferredSize(new Dimension(W,18));
add(space_1_Label);
timeLabel.setFont(new Font("Times New Roman",0,18));
timeLabel.setForeground(new Color(0,0,218));
timeLabel.setBackground(new Color(168,218,238));
timeLabel.setOpaque(true);
timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
timeLabel.setVerticalAlignment(JLabel.CENTER);
timeLabel.setPreferredSize(new Dimension(200,26));
add(timeLabel);
phoneNumberButton.setFont(new Font("Times New Roman",0,18));
phoneNumberButton.setForeground(new Color(0,0,218));
phoneNumberButton.setBackground(new Color(168,218,238));
phoneNumberButton.setHorizontalAlignment(SwingConstants.CENTER);
phoneNumberButton.setVerticalAlignment(JLabel.CENTER);
phoneNumberButton.setMargin(An_Inset);
phoneNumberButton.setPreferredSize(new Dimension(138,26));
add(phoneNumberButton);
setPreferredSize(new Dimension(W,H));
//    Out("Hi");
JLabel space_2_Label = new JLabel();
space_2_Label.setPreferredSize(new Dimension(500,26));
add(space_2_Label);
JPanel messagePanel = new JPanel();
messagePanel.setPreferredSize(new Dimension(518,460));
add(messagePanel);
JTextField userNameField = new JTextField("user_1");
userNameField.setPreferredSize(new Dimension(413,30));
messagePanel.add(userNameField);
JButton connectButton = new JButton("Connect");
connectButton.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent mouseEvent)
{
if (SwingUtilities.isLeftMouseButton(mouseEvent))
{
System.out.println("Left button pressed.");
}
if (SwingUtilities.isMiddleMouseButton(mouseEvent))
{
System.out.println("Middle button pressed.");
}
if (SwingUtilities.isRightMouseButton(mouseEvent))
{
System.out.println("Right button pressed.");
}
}
public void mouseReleased(MouseEvent mouseEvent)
{
if (SwingUtilities.isLeftMouseButton(mouseEvent))
{
System.out.println("Left button released.");
try
{
chatClient.start();
chatURI = new URI(chatUri + userNameField.getText());
chatRequest = new ClientUpgradeRequest();
//      chatClient.connect(chatSocket,chatURI,chatRequest);
System.out.printf("connectButton :: Connecting to : %s%n",chatURI);
testWebsocketClient = new TestWebsocketClient(chatUri + userNameField.getText(),messageTextArea);
}
catch (Exception e) {   e.printStackTrace(); }
}
if (SwingUtilities.isMiddleMouseButton(mouseEvent))
{
System.out.println("Middle button released.");
}
if (SwingUtilities.isRightMouseButton(mouseEvent))
{
System.out.println("Right button released.");
}
System.out.println();
}
});
messagePanel.add(connectButton);
messageTextArea.setFont(new Font("Monospaced",0,12));
messageTextArea.setBackground(new Color(236,236,236));
JScrollPane messageTextAreaScrollPane=new JScrollPane(messageTextArea);
messageTextAreaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
messageTextAreaScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
messageTextAreaScrollPane.setPreferredSize(new Dimension(500,360));
messagePanel.add(messageTextAreaScrollPane);
JTextField messageField = new JTextField("Hello From Frank");
messageField.setPreferredSize(new Dimension(430,30));
messagePanel.add(messageField);
JButton sendButton = new JButton("Send");
sendButton.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent mouseEvent)
{
if (SwingUtilities.isLeftMouseButton(mouseEvent))
{
System.out.println("Left button pressed.");
}
if (SwingUtilities.isMiddleMouseButton(mouseEvent))
{
System.out.println("Middle button pressed.");
}
if (SwingUtilities.isRightMouseButton(mouseEvent))
{
System.out.println("Right button pressed.");
}
}
public void mouseReleased(MouseEvent mouseEvent)
{
if (SwingUtilities.isLeftMouseButton(mouseEvent))
{
System.out.println("Left button released.");
try
{
System.out.printf("messageField.getText() : %s%n",messageField.getText());
System.out.printf("Connecting to : %s%n",chatURI);
testWebsocketClient.sendMessage(messageField.getText());
//                      chatSocket.sendMessage(messageField.getText());
}
catch (Exception e) {   e.printStackTrace(); }
}
if (SwingUtilities.isMiddleMouseButton(mouseEvent))
{
System.out.println("Middle button released.");
}
if (SwingUtilities.isRightMouseButton(mouseEvent))
{
System.out.println("Right button released.");
}
System.out.println();
}
});
messagePanel.add(sendButton);
start();
}
public void run()
{
String timeUri = "ws://127.0.0.1:8080/Dir_WebSocket/endpoint?push=TIME",
phoneNumberUri = "ws://127.0.0.1:8080/Dir_WebSocket/endpoint?push=PHONENUMBER",
whiteboardUri = "ws://127.0.0.1:8080/Dir_WebSocket_Chat_And_Whiteboard/whiteboardendpoint";
//      String destUri = "ws://127.0.0.1:8080/Dir_WebSocket/echo";
WebSocketClient timeClient = new WebSocketClient(),phoneNumberClient = new WebSocketClient(),whiteboardClient = new WebSocketClient();
TimeSocket timeSocket = new TimeSocket(timeLabel);
PhoneNumberSocket phoneNumberSocket = new PhoneNumberSocket(phoneNumberButton);
ChatSocket chatSocket=new ChatSocket(messageTextArea);
URI timeURI,phoneNumberURI,whiteboardURI;
ClientUpgradeRequest timeRequest,phoneNumberRequest,whiteboardRequest;
try
{
timeClient.start();
timeURI = new URI(timeUri);
timeRequest = new ClientUpgradeRequest();
timeClient.connect(timeSocket,timeURI,timeRequest);
System.out.printf("Connecting to : %s%n",timeURI);
//          timesocket.awaitClose(5,TimeUnit.SECONDS);
phoneNumberClient.start();
phoneNumberURI = new URI(phoneNumberUri);
phoneNumberRequest = new ClientUpgradeRequest();
phoneNumberClient.connect(phoneNumberSocket,phoneNumberURI,phoneNumberRequest);
System.out.printf("Connecting to : %s%n",phoneNumberURI);
/*
whiteboardClient.start();
whiteboardURI = new URI(whiteboardUri);
whiteboardRequest = new ClientUpgradeRequest();
chatClient.connect(chatSocket,whiteboardURI,whiteboardRequest);
System.out.printf("Connecting to : %s%n",whiteboardURI);
*/
}
catch (Throwable t) {   t.printStackTrace(); }
finally
{
//          try {   client.stop(); }
//          catch (Exception e) {   e.printStackTrace(); }
}
}
public void start()
{
if (WebSocket_Panel_Thread==null)
{
WebSocket_Panel_Thread=new Thread(this);
WebSocket_Panel_Thread.setPriority(Thread.NORM_PRIORITY);
WebSocket_Panel_Thread.start();
}
}
public void stop() { if (WebSocket_Panel_Thread!=null) WebSocket_Panel_Thread=null; }
private static void out(String message) { System.out.print(message); }
private static void Out(String message) { System.out.println(message); }
// Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread.
static void Create_And_Show_GUI()
{
final WebSocket_Panel demo=new WebSocket_Panel();
JFrame frame=new JFrame("WebSocket_Panel");
frame.add(demo);
frame.addWindowListener( new WindowAdapter()
{
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { demo.repaint(); }
public void windowGainedFocus(WindowEvent e) { demo.repaint(); }
public void windowIconified(WindowEvent e) { }
public void windowLostFocus(WindowEvent e) { }
public void windowOpening(WindowEvent e) { demo.repaint(); }
public void windowOpened(WindowEvent e) { }
public void windowResized(WindowEvent e) { demo.repaint(); }
public void windowStateChanged(WindowEvent e) { demo.repaint(); }
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
// Schedule a job for the event-dispatching thread : creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } });
}
}

enter image description here

When it runs, if I click on “Connect”, it works fine and output the connection message, but when I click on “Send”, it doesn’t work, no message was sent, and there is also no error message, what am I doing wrong, how to send a message ?

How to&Answers:

After several days of experimenting, I figured it out, the message needs to be in a Json format, so instead of sending “Hello From Frank” as a message, it needs to send something like this : {“from”:”null”,”content”:”Hello From Frank”}

Therefore the code should look like this :

Message aMsg=new Message(msg); session.getRemote().sendString(aMsg.getString()); 

==============================================

public class Message { private String from; private String to; private String content; Message(String content) { this.content = content; } @Override public String toString() { return super.toString(); } public String getString() { return "{\"from\":\""+from+"\",\"content\":\""+content+"\"}"; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }