Java websocket client throws exception at send method (TooTallNate) - java

I got a Java project that is supposed to create a websocket client using TooTallNate. Everything seems to be working, connection is succesful to the websocket server but when I call the send method on the socket I get the following:
Exception in thread "Thread-1" org.java_websocket.exceptions.WebsocketNotConnectedException
at org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:608)
at org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:585)
at org.java_websocket.client.WebSocketClient.send(WebSocketClient.java:207)
at Main$2.run(Main.java:39)
at java.lang.Thread.run(Unknown Source)
opened connection
Connection is successfully opened but the send method throws the exception.
I got the following code:
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
public class Main
{
public static void main(String[] args) throws InterruptedException
{
Queue<String> queue = new ConcurrentLinkedQueue<String>();
Runnable producer = new Runnable() {
#Override
public void run() {
for(int i = 0; i < 1000; i++) {
queue.offer(String.valueOf(i));
}
}
};
Thread producerThread = new Thread(producer);
producerThread.start();
Runnable consumer = new Runnable() {
#Override
public void run() {
wsClient c = null;
try {
c = new wsClient( new URI( "ws://echo.websocket.org") );
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.connect();
c.send("hello");
while(true) {
String value = queue.poll();
if(value.equals("100")){
return;
}
System.out.println(value);
}
}
};
Thread consumerThread = new Thread(consumer);
consumerThread.start();
producerThread.join();
consumerThread.join();
}
}
Which simply creates a queue, adds data to it and then polls data from it while at the same time creating a websocket connection to a websocket server but as soon as I try to send data via the socket it throws the exception. Does someone know what could be the issue?

Here you have used connect() method, This is a non blocking method, which is starting the connection/handshake etc.
If you wanna send a frame right after connecting, please use the method connectBlocking() instead of connect().
connectBlocking() method blocks the thread till the connection is established
All credits go to https://github.com/TooTallNate/Java-WebSocket/issues/642

Related

How to perform unit test on a server socket?

I am a beginner in Java. I have built a client-server group chat application watching tutorials. I read a lot about unit tests and can implement in simple maths problems but i don't know how does it work out for complex codes. So I want to see a demo of that which will make it easy to understand testing for rest parts. One part of the code is the 'server' class and it is:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
//import java.awt.event.*;
public class Server {
private final ServerSocket s;
public Server(ServerSocket serverSocket)
{
this.s = serverSocket;
//this.display = display;
}
public void startServer() {
try {
// Listen for connections (clients to connect) on port 1234.
while (!s.isClosed()) {
// Will be closed in the Client Handler.
Socket socket = s.accept();
System.out.println("A new client has connected!");
ClientHandler clientHandler = new ClientHandler(socket);
Thread thread = new Thread(clientHandler);
// The start method begins the execution of a thread.
// When you call start() the run method is called.
// The operating system schedules the threads.
thread.start();
}
} catch (IOException e) {
closeServerSocket();
}
}
// Close the server socket gracefully.
public void closeServerSocket() {
try {
if (s != null) {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Run the program.
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(1234);
Server server = new Server(s);
server.startServer();
}
}
and the test I want to perform are:
import static org.junit.Assert.*;
public class ServerTeste {
#org.junit.Test
public void startServer() {
}
#org.junit.Test
public void closeServerSocket() {
f
}
}
#org.junit.Test
public void main() {
}
}
NB: Apologies for any mistake because I am complete beginner.
Start the server in a separate thread, and connect to it like you would normally do

stop thread with udp server

I've got an UDP server class which implements Runnable interface. I start it in the thread.
The problem is that I can't stop it. Even in Debug it stops on pt.join() method.
Here is my server class
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Network implements Runnable {
final int port = 6789;
DatagramSocket socket;
byte[] input = new byte[1024];
byte[] output = new byte[1024];
public Network() throws SocketException{
socket = new DatagramSocket(6789);
}
#Override
public void run() {
while(true){
DatagramPacket pack = new DatagramPacket(input,input.length);
try {
socket.receive(pack);
} catch (IOException e) {
e.printStackTrace();
}
input = pack.getData();
System.out.println(new String(input));
output = "Server answer".getBytes();
DatagramPacket sendpack = new DatagramPacket(output,output.length,pack.getAddress(),pack.getPort());
try {
socket.send(sendpack);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This is the main class
public class Main {
static Network network = null;
public static void main(String[] args) throws IOException{
network = new Network();
System.out.println("Try to start server");
Thread pt = new Thread(network);
pt.start();
pt.interrupt();
try {
pt.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Stop server");
}
}
How to stop server?
java.net reads are non-interruptible. You would have to either close the DatagramSocket or have it read with a timeout (setSoTimeout()), and when you get the resulting SocketTimeoutException check the interrupt status: if set, exit the thread.
Calling interrupt doesn't actually stop the thread, it just sets a flag.
Inside your loop, check for isInterrupted(). e.g., a quick and dirty way would be change
while(true)
to
while (!Thread.currentThread().isInterrupted())
But you should consult some more documentation if you get more serious about this project.
As mentioned by #EJP, if you are hanging in the Socket IO, you'll need to close the Socket or have a timeout.
In addition to what EJP said, you probably should have a local boolean called running (or whatever), and set it to true before you enter your while loop. Have your while loop be conditioned on this local boolean. And provide methods (stopServer() and isRunning()) to set and check the status of the boolean. You also might want to remove the try-catch from inside the while loop and put the entire while loop within a try-catch-finally and in the finally statement perform clean-up (set running=false; close the connection, etc)

NullPointerException in Thread's run method

I would really appreciate help with my program. It is some sort of chat server with multiple clients.
Here's the server code:
package com.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static int PORT;
private ServerSocket server;
private Socket socket;
public Server(int port) throws IOException {
PORT = port;
server = new ServerSocket(PORT);
System.out.println("server started");
try {
while (true) {
socket = server.accept();
try {
new ServeClient(socket);
} catch (IOException e) {
socket.close();
}
}
} finally {
server.close();
}
}
public static void main(String[] args) throws IOException {
int port = Integer.parseInt(args[0]);
Server server = new Server(port);
}
}
I start the server and then create a Client. The server receives connection socket from socket
and creates a ServeClient Thread.
Here's ServeClient code:
package com.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;
import com.gui.WindowManager;
public class ServeClient extends Thread {
private final Socket socket;
private BufferedReader in;
private PrintWriter out;
private String msg;
public static final String ENDSTRING = "END";
public static Vector clients = new Vector();
public ServeClient(final Socket socket) throws IOException {
this.socket = socket;
System.out.println("socket " + socket);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
start();
}
public void run() {
try {
clients.add(this);
while (true) {
msg = in.readLine();
if (msg == ENDSTRING)
break;
broadcast(msg);
}
System.out.println("closing...");
} catch (IOException e) {
System.err.println("IO EXCEPTION");
} finally {
try {
socket.close();
} catch (IOException e) {
System.err.println("SOCKET NOT CLOSED");
}
}
}
#SuppressWarnings("deprecation")
public void broadcast(String msg) {
synchronized (clients) {
Enumeration<ServeClient> e = clients.elements();
while (e.hasMoreElements()) {
ServeClient serveClient = e.nextElement();
try {
synchronized (serveClient.out) {
serveClient.out.println(msg);
}
} catch (Exception eee) {
serveClient.stop();
}
}
}
}
}
What i get is a NullPointerException when ServeClient invokes run() method
server started
socket Socket[addr=/127.0.0.1,port=51438,localport=8888]
Exception in thread "Thread-0" java.lang.NullPointerException
at com.server.ServeClient.run(ServeClient.java:33)
line 33 is the line with first "try" statement in ServeClient run() method
com.server.ServeClient.run(ServeClient.java:33)
I don't believe that it's happening at the try.
Open up an IDE, turn on debugging, and step through until you can see what's happening. That's the fastest way to figure out what you've missed.
There's an object that you're assuming is fine that is not. Find it.
Here's an example of how to do this properly:
http://www.kodejava.org/examples/216.html
Your problem is with the order in which static instance variables are initialised. Try doing something like:
...
private static Vector clients = null;
...
if (clients==null) {
clients = new Vector(); // consider putting this in a synchronized block
}
before you add the client to the vector.
Sorry for necroing such an old issue but it seemed like this problem wasn't resolved, so I'll give a bit of input from my end.
I've had a similar problem and the compiler also kept telling me that the problem was at the start() method. However, when I commented out the thread part and just ran the code on the same thread as the UI, the compiler directed me to the real source of the problem: the code inside the thread.
After making sure the code didn't give an error, I enclosed the code with the original thread code, and it stopped giving me the NullPointerException error.
Hope this helps someone along the way.
Remove the duplicate class declaration in JPanel.
I was trying to run a timer thread that updated a clock in the main application window.
I had created the JFrame with Eclipse/WindowBuilder and had followed a tutorial on how to make a timer. I had copied the declaration of the textfield into the class declaration to make it available for the entire class, but forgot to remove the Class Id in front of the widget definition. So it still initialized the local instance and not the global one. Thus when I accessed the global one it was still null.

Shifting from blocking to non-blocking I/O with javanio

i adapt this code How to send and receive serialized object in socket channel my real time simulation to send objects but i am running into exceptions one after another is it because this code blocking in nature how this code can be converted in to non blocking with javanio
/*
* Writer
*/
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class CleanSender implements Runnable {
private SimManager SM;
private BallState ballState = new BallState(10, 5);
private ServerSocketChannel ssChannel;
private Thread tRunSer = new Thread(this, "ServerSelectThread");
public static void main(String[] args) throws IOException {
CleanSender server = new CleanSender();
server.startServer();
}
private void startServer() throws IOException {
ssChannel = ServerSocketChannel.open();
ssChannel.configureBlocking(true);
int port = 2345;
ssChannel.socket().bind(new InetSocketAddress(port));
// SM = new SimManager(this, BS);
// SM.start(); // GameEngine thread starting here
tRunSer.start();
}
public void run() {
try {
SocketChannel sChannel = ssChannel.accept();
while (true) {
ObjectOutputStream oos = new ObjectOutputStream(sChannel
.socket().getOutputStream());
oos.writeObject(ballState);
System.out.println("Sending String is: '" + ballState.X + "'" + ballState.Y);
oos.close();
System.out.println("Sender Start");
System.out.println("Connection ended");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client: which is continously looking for reply from server
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class CleanReceiver implements Runnable {
private SocketChannel sChannel;
private Thread receiverThread = new Thread(this, "receiverThread");
private synchronized void startServer() throws IOException {
sChannel = SocketChannel.open();
sChannel.configureBlocking(true);
if (sChannel.connect(new InetSocketAddress("localhost", 2345))) {
receiverThread.start();
}
}
public void run() {
while (true) {
try {
ObjectInputStream ois = new ObjectInputStream(sChannel.socket()
.getInputStream());
BallState s = (BallState) ois.readObject();
System.out.println("String is: '" + s.X + "'" + s.Y);
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("End Receiver");
}
}
public static void main(String[] args)
throws IOException, ClassNotFoundException {
CleanReceiver rc=new CleanReceiver();
rc.startServer();
System.out.println("End Receiver");
}
}
Will this design work in the scenario when server has to keep connect the client and simultaneous send the simulation state to already connected client?, i m looking for experts glance.
thanks,
jibbylala
If you are using ObjectInputStream or ObjectOutputStream I suggest you stick with blocking IO. Using non-blocking IO with these libraries is 10x harder for no real benifit.
Have you considered using ServerSocket and Socket instead of NIO. These will be easier to use and what the object streams were originall designed to use,
Your code have two main problems:
You close streams after handling every single object, that causes closing of the associated sockets, so they are no longer valid and cannot be used for processing the following objects. At the receiving side you don't need close() inside a loop at all, at the sending side use flush() instead of close() to ensure that buffers are flushed.
When implementing blocking IO you (usually) need to start a new thread on the server for each client. It would allow you to communicate with multiple clients simultaneously. Beware of thread synchronization problems in this case!
If having a thread per client is not acceptable for you, you can implement server in a non-blocking way, but, as already said by Peter Lawrey, it's more complex, so I suggest you to get it working with blocking IO first.

Using Threads to Handle Sockets

I am working on a java program that is essentially a chat room. This is an assignment for class so no code please, I am just having some issues determining the most feasible way to handle what I need to do. I have a server program already setup for a single client using threads to get the data input stream and a thread to handle sending on the data output stream. What I need to do now is create a new thread for each incoming request.
My thought is to create a linked list to contain either the client sockets, or possibly the thread. Where I am stumbling is figuring out how to handle sending the messages out to all the clients. If I have a thread for each incoming message how can I then turn around and send that out to each client socket.
I'm thinking that if I had a linkedlist of the clientsockets I could then traverse the list and send it out to each one, but then I would have to create a dataoutputstream each time. Could I create a linkedlist of dataoutputstreams? Sorry if it sounds like I'm rambling but I don't want to just start coding this, it could get messy without a good plan. Thanks!
EDIT
I decided to post the code I have so far. I haven't had a chance to test it yet so any comments would be great. Thanks!
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.LinkedList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class prog4_server {
// A Queue of Strings used to hold out bound Messages
// It blocks till on is available
static BlockingQueue<String> outboundMessages = new LinkedBlockingQueue<String>();
// A linked list of data output streams
// to all the clients
static LinkedList<DataOutputStream> outputstreams;
// public variables to track the number of clients
// and the state of the server
static Boolean serverstate = true;
static int clients = 0;
public static void main(String[] args) throws IOException{
//create a server socket and a clientSocket
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(6789);
} catch (IOException e) {
System.out.println("Could not listen on port: 6789");
System.exit(-1);
}// try{...}catch(IOException e){...}
Socket clientSocket;
// start the output thread which waits for elements
// in the message queue
OutputThread out = new OutputThread();
out.start();
while(serverstate){
try {
// wait and accept a new client
// pass the socket to a new Input Thread
clientSocket = serverSocket.accept();
DataOutputStream ServerOut = new DataOutputStream(clientSocket.getOutputStream());
InputThread in = new InputThread(clientSocket, clients);
in.start();
outputstreams.add(ServerOut);
} catch (IOException e) {
System.out.println("Accept failed: 6789");
System.exit(-1);
}// try{...}catch{..}
// increment the number of clients and report
clients = clients++;
System.out.println("Client #" + clients + "Accepted");
}//while(serverstate){...
}//public static void main
public static class OutputThread extends Thread {
//OutputThread Class Constructor
OutputThread() {
}//OutputThread(...){...
public void run() {
//string variable to contain the message
String msg = null;
while(!this.interrupted()) {
try {
msg = outboundMessages.take();
for(int i=0;i<outputstreams.size();i++){
outputstreams.get(i).writeBytes(msg + '\n');
}// for(...){...
} catch (IOException e) {
System.out.println(e);
} catch (InterruptedException e){
System.out.println(e);
}//try{...}catch{...}
}//while(...){
}//public void run(){...
}// public OutputThread(){...
public static class InputThread extends Thread {
Boolean threadstate = true;
BufferedReader ServerIn;
String user;
int threadID;
//SocketThread Class Constructor
InputThread(Socket clientSocket, int ID) {
threadID = ID;
try{
ServerIn = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
user = ServerIn.readLine();
}
catch(IOException e){
System.out.println(e);
}
}// InputThread(...){...
public void run() {
String msg = null;
while (threadstate) {
try {
msg = ServerIn.readLine();
if(msg.equals("EXITEXIT")){
// if the client is exiting close the thread
// close the output stream with the same ID
// and decrement the number of clients
threadstate = false;
outputstreams.get(threadID).close();
outputstreams.remove(threadID);
clients = clients--;
if(clients == 0){
// if the number of clients has dropped to zero
// close the server
serverstate = false;
ServerIn.close();
}// if(clients == 0){...
}else{
// add a message to the message queue
outboundMessages.add(user + ": " + msg);
}//if..else...
} catch (IOException e) {
System.out.println(e);
}// try { ... } catch { ...}
}// while
}// public void run() { ...
}
public static class ServerThread extends Thread {
//public variable declaration
BufferedReader UserIn =
new BufferedReader(new InputStreamReader(System.in));
//OutputThread Class Constructor
ServerThread() {
}//OutputThread(...){...
public void run() {
//string variable to contain the message
String msg = null;
try {
//while loop will continue until
//exit command is received
//then send the exit command to all clients
msg = UserIn.readLine();
while (!msg.equals("EXITEXIT")) {
System.out.println("Enter Message: ");
msg = UserIn.readLine();
}//while(...){
outboundMessages.add(msg);
serverstate = false;
UserIn.close();
} catch (IOException e) {
System.out.println(e);
}//try{...}catch{...}
}//public void run(){...
}// public serverThread(){...
}// public class prog4_server
I have solved this problem in the past by defining a "MessageHandler" class per client connection, responsible for inbound / outbound message traffic. Internally the handler uses a BlockingQueue implementation onto which outbound messages are placed (by internal worker threads). The I/O sender thread continually attempts to read from the queue (blocking if required) and sends each message retrieved to the client.
Here's some skeleton example code (untested):
/**
* Our Message definition. A message is capable of writing itself to
* a DataOutputStream.
*/
public interface Message {
void writeTo(DataOutputStream daos) throws IOException;
}
/**
* Handler definition. The handler contains two threads: One for sending
* and one for receiving messages. It is initialised with an open socket.
*/
public class MessageHandler {
private final DataOutputStream daos;
private final DataInputStream dais;
private final Thread sender;
private final Thread receiver;
private final BlockingQueue<Message> outboundMessages = new LinkedBlockingQueue<Message>();
public MessageHandler(Socket skt) throws IOException {
this.daos = new DataOutputStream(skt.getOutputStream());
this.dais = new DataInputStream(skt.getInputStream());
// Create sender and receiver threads responsible for performing the I/O.
this.sender = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
Message msg = outboundMessages.take(); // Will block until a message is available.
try {
msg.writeTo(daos);
} catch(IOException ex) {
// TODO: Handle exception
}
}
}
}, String.format("SenderThread-%s", skt.getRemoteSocketAddress()));
this.receiver = new Thread(new Runnable() {
public void run() {
// TODO: Read from DataInputStream and create inbound message.
}
}, String.format("ReceiverThread-%s", skt.getRemoteSocketAddress()));
sender.start();
receiver.start();
}
/**
* Submits a message to the outbound queue, ready for sending.
*/
public void sendOutboundMessage(Message msg) {
outboundMessages.add(msg);
}
public void destroy() {
// TODO: Interrupt and join with threads. Close streams and socket.
}
}
Note that Nikolai is correct in that blocking I/O using 1 (or 2) threads per connection is not a scalable solution and typically applications might be written using Java NIO to get round this. However, in reality unless you're writing an enterprise server which thousands of clients connect to simultaneously then this isn't really an issue. Writing bug-free scalable applications using Java NIO is difficult and certainly not something I'd recommend.

Categories

Resources