I can't figure out why nothing happens.
I'm trying to write a java program that sends a json object to a jetty server.
The server is already written(by someone else,its an project) and only excepts certain json objects. But he doesn't get anything from my program.
public class client {
final static String HOST = "localhost";
final static int PORT = 3000;
public static void main(String[] args)
{
String URIString = "ws://" + HOST + ":" + PORT + "/servlets";
URI uri = URI.create(URIString);
WebSocketClient client = new WebSocketClient();
JSONObject js = new JSONObject();
js.put("toke","hallo");
Clientsocket clientsocket = new Clientsocket();
try {
client.start();
Future<Session> fut = client.connect(clientsocket, uri);
clientsocket.getSession().getRemote().sendString(js.toJSONString());;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class Clientsocket extends WebSocketAdapter {
//private static final Logger LOG = Log.getLogger(Clientsocket.class);
#Override
public void onWebSocketClose(int statusCode,String reason)
{
super.onWebSocketClose(statusCode, reason);
//LOG.info("Websocket Close:{} - {} ", statusCode,reason);
}
#Override
public void onWebSocketConnect(Session session)
{
super.onWebSocketConnect(session);
//LOG.info("Websocket Connect: {}", session);
}
}
error message when started:
2018-06-22 14:26:43.789:INFO::main: Logging initialized #257ms to org.eclipse.jetty.util.log.StdErrLog
java.lang.NullPointerException
[both classes: clientsocket, client][1]
I think you didn't wait for the connect to complete.
Future<Session> fut = client.connect(clientsocket, uri);
Session session = fut.get(); // wait for connect to complete (or throw exception)
session.getRemote().sendString(js.toJSONString());
Related
I am implementing an FTP server in Java for a project. I can start the server but when I try to connect with a client it is stuck on "waiting for welcome message". I've looked at several examples but I'm not sure where I'm going wrong. Here is the class I have. I will eventually break some of this out into other methods.
The user parameters have been cleared for the purposes of this post.
public class FTPServer {
final int PORT = 2221;
String userfile = "";
String username="";
String password = ""
String homedir ="";
private FtpServer server=null;
public FTPServer() {}
public FTPServer(final String ipaddress, final int port){
FtpServerFactory serverFactory = new FtpServerFactory();
ListenerFactory listenerfactory = new ListenerFactory();
listenerfactory.setDataConnectionConfiguration(
new DataConnectionConfigurationFactory().createDataConnectionConfiguration());
ConnectionConfigFactory connection = new ConnectionConfigFactory();
connection.setMaxLoginFailures(10);
connection.setLoginFailureDelay(5);
connection.setAnonymousLoginEnabled(false);
// set the ip address of the listener
listenerfactory.setServerAddress(ipaddress);
// set the port of the listener
if (port == 0)
{ listenerfactory.setPort(PORT);}
else {listenerfactory.setPort(port);
// replace the default listener
serverFactory.addListener("default", listenerfactory.createListener());
serverFactory.setConnectionConfig(connection.createConnectionConfig());
}
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(new File(userfile));
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
UserManager um = userManagerFactory.createUserManager();
BaseUser user = new BaseUser();
user.setName(username);
user.setPassword(password);
user.setHomeDirectory(homedir);
try {
um.save(user);
} catch (FtpException e1) {
// TODO Auto-generated catch block
this.StopServer();
e1.printStackTrace();
}
serverFactory.setUserManager(um);
server = serverFactory.createServer();
}
public void StopServer(){ this.server.stop(); }
public void StartServer()
{
try {
server.start();
} catch (FtpException e) {
// handle this eventually, good enough for testing now
e.printStackTrace();
}
}
Here is the code that creates the server and starts and stops it
final int port = 0;
final String ipaddress = "";
FTPServer server = new FTPServer(ipaddress,port);
server.StartServer();
server.StopServer();
I'd say that FtpServer.Start only starts listening on the incoming port. It does not block. You kill the server immediately afterwards by calling .Stop.
You have to wait in your code explicitly to keep the server running.
server.StartServer();
Thread.sleep(Long.MAX_VALUE);
I am trying to develop a JavaFx application for testing an IPTV. And my task is checking of channel changing successfully. There is no any component or device at the moment. But I am searching for this task, after that I will buy.
My application will send some remote control command over the IR device.
Here is an IR device, but It doesn't have a Java API.
Is there a way for this solution?
I searched and found a device which name was RedRat. It is usb-infrared device that we can use it linux and windows OS.
There is a utility for using it with a programming language.
Here is a sample java code, may be useful for somebody. But you should have a redrat device.
First step, you have to download this redRatHub and paste a direction
secondly, run main class which has same path with redrathub folders.
public class MyDemo {
private static Client client;
private static String DEVICE_NAME = "";
private static String DATA_SET = "";
public static void main(String[] args) {
try {
startRedRat();
client = new Client();
client.openSocket("localhost", 40000);
DEVICE_NAME = client.readData("hubquery=\"list redrats\"").split("]")[1].split("\n")[0].trim();
DATA_SET = client.readData("hubquery=\"list datasets\"").split("\n")[1];
sendCommand("power");
TimeUnit.SECONDS.sleep(5);
sendCommand("btn1", "btn1", "btn1", "btn1");
sendCommand("btnOK");
TimeUnit.SECONDS.sleep(30);
sendCommand("btnBACK");
sendCommand("channel+");
sendCommand("btn6", "btn1");
sendCommand("channel+");
sendCommand("channel-");
sendCommand("volume+");
sendCommand("volume-");
sendCommand("power");
client.closeSocket();
p.destroy();
} catch (Exception ex) {
System.err.println(ex.getMessage());
} finally {
System.out.println("Finished. Hit <RETURN> to exit...");
}
}
private static void sendCommand(String... command) {
try {
for (String cmd : command) {
client.sendMessage("name=\"" + DEVICE_NAME + "\" dataset=\"" + DATA_SET + "\" signal=\"" + cmd + "\"");
TimeUnit.MILLISECONDS.sleep(500);
System.out.println(cmd + " signal send");
}
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void startRedRat() {
try {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
p = Runtime.getRuntime().exec("cmd /C C:\\RedRatHub\\RedRatHubCmd.exe C:\\RedRatHub\\TivibuDB.xml");
return null;
}
};
worker.run();
TimeUnit.SECONDS.sleep(5);
} catch (Exception e) {
e.printStackTrace();
}
}
}
this class is communicate with redrat device over the serial ports.
public class Client {
private Socket socket;
private DataOutputStream out;
private DataInputStream in;
/*
* Opens the socket to RedRatHubCmd.
*/
public void openSocket(String host, int port) throws UnknownHostException, IOException {
if (socket != null && socket.isConnected()) return;
socket = new Socket(host, port);
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
}
/*
* Closes the RedRatHubCmd socket.
*/
public void closeSocket() throws IOException {
socket.close();
}
/*
* Sends a message to the readData() method. Use when returned data from RedRatHub is not needed.
*/
public void sendMessage(String message) throws Exception {
String res = readData(message);
if (!res.trim().equals("OK")) {
throw new Exception("Error sending message: " + res);
}
}
/*
* Reads data back from RedRatHub. Use when returned data is needed to be output.
*/
public String readData(String message) throws IOException {
if (socket == null || !socket.isConnected()) {
System.out.println("\tSocket has not been opened. Call 'openSocket()' first.");
return null;
}
// Send message
out.write((message + "\n").getBytes("UTF-8"));
// Check response. This is either a single line, e.g. "OK\n", or a multi-line response with
// '{' and '}' start/end delimiters.
String received = "";
byte[] inBuf = new byte[256];
while (true) {
// Read data...
int inLength = in.read(inBuf);
//byte[] thisMSg = new byte[inLength];
String msg = new String(Arrays.copyOfRange(inBuf, 0, inLength), "UTF-8");
received += msg;
if (checkEom(received)) return received;
}
}
/*
* Checks for the end of a message
*/
public boolean checkEom(String message) {
// Multi-line message
if (message.trim().endsWith("}")) {
return message.startsWith("{");
}
// Single line message
return message.endsWith("\n");
//return true;
}
}
I'm trying to implement a Server-Sent-Events Client using Jersey 2.5.1 (can't upgrade to a later version), and the connection keeps getting closed, with no events being read.
I've reduced the code to what I believe is the simplest following possible from the manual, but without success.
I have tested my client against other servers, and the behaviour is the same, so I believe my problem is client based.
The client connects to the resource, and the server starts sending events. But no events are received, and the connection is closed prematurely.
I've also tried using EventSource instead of EventInput, but the results are the same.
Can someone please tell me what I'm missing? Thanks.
Server Code:
#Path("events")
public class SseResource {
/**
* Create stream.
* #return chunkedOutput of events.
*/
#GET
#Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput getServerSentEvents() {
System.out.println("Received GetEvent");
final EventOutput eventOutput = new EventOutput();
new Thread(new Runnable() {
#Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
final OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
eventBuilder.name("message-to-client");
eventBuilder.data(String.class, "Hello world " + i + "!");
final OutboundEvent event = eventBuilder.build();
eventOutput.write(event);
System.out.println("Wrote event " + i);
// ... code that waits 1 second
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (IOException e) {
System.out.println("Error when writing the event" + e);
throw new RuntimeException("Error when writing the event.", e);
} finally {
try {
eventOutput.close();
} catch (IOException ioClose) {
System.out.println("Error when closing the eventOuput" + ioClose);
throw new RuntimeException("Error when closing the event output.", ioClose);
}
}
}
}).start();
return eventOutput;
}
}
Client Code:
import org.glassfish.jersey.media.sse.EventInput;
import org.glassfish.jersey.media.sse.InboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
...
public final void simpleClientTest() {
final Client client = ClientBuilder.newBuilder().register(SseFeature.class).build();
final WebTarget target = client.target("http://localhost:8182/events");
final EventInput eventInput = target.request().get(EventInput.class);
while (!eventInput.isClosed()) {
final InboundEvent inboundEvent = eventInput.read();
if (inboundEvent == null) {
// connection has been closed
break;
}
System.out.println(inboundEvent.getName() + "; " + inboundEvent.readData(String.class));
}
System.out.println("eventInput finished");
}
I have, finally, found the cause of the problem. The server-startup code (not given above) did not include the SseFeature.class resource. Including here in-case someone else has this issue....
public void startServer() throws IOException {
final URI baseUri = UriBuilder.fromUri("http://0.0.0.0").port(serverPort).build();
System.out.println("Starting media server at: " + baseUri);
final ResourceConfig config = new ResourceConfig(SseResource.class, SseFeature.class);
server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
}
I need to test some client/server application using JUnit and I'm having trouble testing the connection of a client to the server. It seems that the test hangs at the "Socket clientSocket = serverSocket.accept()" line in the server class, and it's not letting me connect a new client.
Here's the JUnit class:
#Test
public void testNetServerComm_1() throws Exception {
server = new NetServerComm();
assertNotNull(server);
}
#Test
public void testAddMessageToQueue_1() throws Exception {
NetServerComm fixture = new NetServerComm();
NetServerSideMessage msg = new NetServerSideMessage(birdsong.comm.ServerSideMessage.Type.BIRDSONG_MESSAGE, "",
"");
fixture.addMessageToQueue(msg);
assertEquals(1, fixture.getMsgQueueSize());
}
#Test
public void testClientIsConnected_1() throws Exception {
NetServerComm fixture = new NetServerComm();
fixture.start();
//test doesn't go further that this..
String nickname = "john";
new NetClientComm().connect("127.0.0.1", nickname);
boolean result = fixture.isClientConnected(nickname);
assertTrue(result);
}
Client Class:
//connects to the server
#Override
public void connect(String host, String nickname) {
try {
clientNickname = nickname;
System.out.println("Address= " + host + " and NickName = " + nickname);
socket = new Socket(host, NetServerComm.PORTO); //8080
System.out.println("Socket = " + socket);
serverMsg = new NetServerSideMessage(ServerSideMessage.Type.CLIENT_CONNECTED, null, clientNickname);
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(serverMsg);
isConnected = true;
messageHandler = new Thread(new MessageHandler(socket));
messageHandler.start();
} catch (IOException e) {
System.out.println("Failed connecting to the server.");
e.printStackTrace();
}
}
Server Class:
//starts the server
#Override
public void start() {
try {
serverSocket = new ServerSocket(PORTO); //8080
System.out.println("Servidor is online: " + serverSocket);
try {
while (true) {
Socket clientSocket = serverSocket.accept();
//test hangs at the method above^^^
checkNewClient(clientSocket);
if (nameCheck == true)
new Thread(new ClientHandler(clientSocket)).start();
}
} finally {
System.out.println("Closing the server..");
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
It looks like you start() method is getting executed by the same Thread as the test, so it blocks there (at the accept() part). Could you try to have this method executed by a new Thread instead ? – Berger
That seems to have done the job :) – JDev
I'm trying to implement OSGI bundle with network server which uses network sockets.
This is the complete source code: http://www.2shared.com/file/RMXby331/CB_27.html
This is the Activator:
package org.DX_57.osgi.CB_27.impl;
import java.util.Properties;
import org.DX_57.osgi.CB_27.api.CBridge;
import org.DX_57.osgi.CB_27.impl.EchoServer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
public class CBridgeApp implements BundleActivator {
public void start(BundleContext bc) throws Exception {
ServiceRegistration registerService = bc.registerService(CBridge.class.getName(), new CBridgeImpl(), new Properties());
EchoServer();
}
public void stop(BundleContext bc) throws Exception {
boolean ungetService = bc.ungetService(bc.getServiceReference(CBridge.class.getName()));
}
private void EchoServer() {
EchoServer method = new EchoServer();
}
}
This is the source code if the Java Network server:
package org.DX_57.osgi.CB_27.impl;
import java.net.*;
import java.io.*;
public class EchoServer
{
ServerSocket m_ServerSocket;
public EchoServer()
{
try
{
// Create the server socket.
m_ServerSocket = new ServerSocket(12111);
}
catch(IOException ioe)
{
System.out.println("Could not create server socket at 12111. Quitting.");
System.exit(-1);
}
System.out.println("Listening for clients on 12111...");
// Successfully created Server Socket. Now wait for connections.
int id = 0;
while(true)
{
try
{
// Accept incoming connections.
Socket clientSocket = m_ServerSocket.accept();
// accept() will block until a client connects to the server.
// If execution reaches this point, then it means that a client
// socket has been accepted.
// For each client, we will start a service thread to
// service the client requests. This is to demonstrate a
// multithreaded server, although not required for such a
// trivial application. Starting a thread also lets our
// EchoServer accept multiple connections simultaneously.
// Start a service thread
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
}
catch(IOException ioe)
{
System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
}
public static void main (String[] args)
{
new EchoServer();
}
class ClientServiceThread extends Thread
{
Socket m_clientSocket;
int m_clientID = -1;
boolean m_bRunThread = true;
ClientServiceThread(Socket s, int clientID)
{
m_clientSocket = s;
m_clientID = clientID;
}
public void run()
{
// Obtain the input stream and the output stream for the socket
// A good practice is to encapsulate them with a BufferedReader
// and a PrintWriter as shown below.
BufferedReader in = null;
PrintWriter out = null;
// Print out details of this connection
System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " +
m_clientSocket.getInetAddress().getHostName());
try
{
in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
// At this point, we can read for input and reply with appropriate output.
// Run in a loop until m_bRunThread is set to false
while(m_bRunThread)
{
// read incoming stream
String clientCommand = in.readLine();
System.out.println("Client Says :" + clientCommand);
if(clientCommand.equalsIgnoreCase("quit"))
{
// Special command. Quit this thread
m_bRunThread = false;
System.out.print("Stopping client thread for client : " + m_clientID);
}
else
{
// Echo it back to the client.
out.println(clientCommand);
out.flush();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
// Clean up
try
{
in.close();
out.close();
m_clientSocket.close();
System.out.println("...Stopped");
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
}
When I try to deploy the bundle on Glassfish server the application server hangs but I can connect to the java network server using the java client. It seems that there is a infinite loop. I need help to fix the code.
Best wishes
Your bundle activator start method never returns, because you're calling constructor of your service with infinite loop. A good practice is to return as fast as possible from bundle activators.
Here is an idea how to rewrite your code:
public class EchoServer {
private volatile boolean started;
public void start() {
new Thread(new Runnable() {
#Override
public void run() {
started = true;
try {
m_ServerSocket = new ServerSocket(12111);
} catch(IOException ioe) {
System.out.println("Could not create server socket at 12111. Quitting.");
System.exit(-1);
}
System.out.println("Listening for clients on 12111...");
// Successfully created Server Socket. Now wait for connections.
int id = 0;
while (started) {
try {
Socket clientSocket = m_ServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
} catch(IOException ioe) {
System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
}
}).start();
}
public void stop() {
started = false;
}
}
Activator
public class CBridgeApp implements BundleActivator {
private EchoServer method;
public void start(BundleContext bc) throws Exception {
...
method = new EchoServer();
method.start();
}
public void stop(BundleContext bc) throws Exception {
...
method.stop();
}
}