I want to send a String to a Telnet Connection using TelnetConnection from Apache
import java.io.IOException;
import org.apache.commons.net.telnet.TelnetClient;
public class TestClass {
public static void main(String[] args) throws IOException, InterruptedException {
String telnetServer = "123.456.789.123";
int telnetPort = 32106;
TelnetClient telnet = new TelnetClient();
try {
telnet.connect(telnetServer, telnetPort);
String start = "start";
telnet.getOutputStream().write(start.getBytes());
telnet.getOutputStream().flush();
System.out.println(telnet.getInputStream());
} catch (Exception e) {
System.out.println(e);
}finally {
telnet.disconnect();
}
}
}
However, I don't get a result. How do I use Input and Output Stream in this case?
The command ("start") should start the recording of METUS INGEST 5.6.
Thanks to Some programmer dude(https://stackoverflow.com/users/440558/some-programmer-dude). This totally did the job.
Here is the complete code:
import java.io.IOException;
import org.apache.commons.net.telnet.TelnetClient;
public class TestClass {
public static void main(String[] args) throws IOException, InterruptedException {
String telnetServer = "123.456.789.123";
int telnetPort = 32106;
TelnetClient telnet = new TelnetClient();
try {
telnet.connect(telnetServer, telnetPort);
String start = "start\r\n";
telnet.getOutputStream().write(start.getBytes());
telnet.getOutputStream().flush();
System.out.println(telnet.getInputStream());
} catch (Exception e) {
System.out.println(e);
}finally {
telnet.disconnect();
}
}
}
You can stop the recording of all sources with:
String stop = "stop\r\n";
telnet.getOutputStream().write(stop.getBytes());
telnet.getOutputStream().flush();
Related
I want to execute a class method that is present in another file. I am doing the following:
import java.io.IOException;
public class run_java_program {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("java -cp C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src test");
} catch (IOException e) {
e.printStackTrace();
}
}
}
But its not working. However on the cmd it is:
I tried replacing C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src with C:/Users/96171/eclipse-workspace/IR_Project/src but still nothing is printed out to the console.
Here is the other program:
//import py4j.GatewayServer;
public class test {
public static void addNumbers(int a, int b) {
System.out.print(a + b);
}
// public static void addNumbers(int a, int b) {
// System.out.print(a + b);
// }
public static void main(String[] args) {
// GatewayServer gatewayServer = new GatewayServer(new test());
// gatewayServer.start();
// System.out.println("Gateway Server Started");
test t = new test();
t.addNumbers(5, 6);
}
}
The outputstream of the executed program test would become the inputstream for your current program run_java_program. Change your code to this and try:
import java.io.IOException;
public class run_java_program {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("java -cp C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src test");
java.util.Scanner s = new java.util.Scanner(process.getInputStream());
System.out.println(s.nextLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I used Scanner as I know it returns only one line. Based on your need you can also use apache common utils.
this is the scenario .. i have 2 clients connected to a server.. i want them to be able to chat with eachother. After a couple of messages i get this error.
Exception in thread "Thread-0" java.lang.ClassCastException:
java.io.ObjectStreamClass cannot be cast to message.Mesaj
at server.ServerThread.readAndWrite(ServerThread.java:43)
at server.ServerThread.run(ServerThread.java:61)
java.io.StreamCorruptedException: invalid type code: 00
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at server.ServerThread.readAndWrite(ServerThread.java:43)
at server.ServerThread.run(ServerThread.java:61)
This is the client:
package client;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
import message.Mesaj;
public class Client {
public static int port=4321;
public static Socket socket;
public static ObjectOutputStream oo;
public static ObjectInputStream oi;
public static Scanner sc;
public Client() throws IOException{
socket = new Socket ("localhost",4321);
oi = new ObjectInputStream(socket.getInputStream());
oo = new ObjectOutputStream(socket.getOutputStream());
}
public static void listen() throws ClassNotFoundException, IOException{
while(true){
Mesaj m = (Mesaj) oi.readObject();
if(m!=null){
System.out.println("mesajul este: " + m.getMesaj());
}
}
}
public static void write() throws IOException{
sc= new Scanner(System.in);
while(true){
String trimite= sc.nextLine();
Mesaj m = new Mesaj();
m.setMesaj(trimite);
oo.writeObject(m);
oo.flush();
}
}
public static Thread t = new Thread(){
public void run(){
try {
listen();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public static Thread t2 = new Thread(){
public void run(){
try {
write();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public static void main(String[] args) throws IOException{
new Client();
t.start();
t2.start();
}
This is the Server:
package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
public int port;
public static Socket socket;
public static ServerSocket serverSocket;
public Server() throws IOException{
this.port=4321;
serverSocket = new ServerSocket(port);
}
public static void main (String [] args){
try {
new Server();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Server functionabil..asteptam conexiune client");
while(true){
try {
socket= serverSocket.accept();
ServerThread st= new ServerThread(socket);
st.start();
System.out.println("Conexiune realizata -client conectat");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
..and this is the Server Thread:
package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import message.Mesaj;
public class ServerThread extends Thread {
boolean running;
public static ObjectOutputStream oo;
public static ObjectInputStream oi;
public static Mesaj m;
public static Socket socket;
public ServerThread(Socket socket) throws ClassNotFoundException{
try {
running=true;
this.socket=socket;
oo = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readAndWrite() throws ClassNotFoundException, IOException{
oi = new ObjectInputStream(socket.getInputStream());
while(true){
m= (Mesaj) oi.readObject();
if(m!=null){
oo.writeObject(m);
oo.flush();
System.out.println(m.getMesaj());
}
}
}
public void run(){
System.out.println("Server Thread contectat");
try {
readAndWrite();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT:
This is the message class:
package message;
import java.io.Serializable;
public class Mesaj implements Serializable {
private String mesaj;
public String getMesaj() {
return mesaj;
}
public void setMesaj(String mesaj) {
this.mesaj = mesaj;
}
}
You having concurrency issues.
Both serverthreads access the same static outputstream, meaning that there is a change for corruption as Object streams aren't designed for this.
In ServerThread, remove static from all the variables and the method "readAndWrite".
public ObjectOutputStream oo;
public ObjectInputStream oi;
public Mesaj m;
public Socket socket;
...
public void readAndWrite() throws ClassNotFoundException, IOException{
If you want to access the output streams from multiple threads, you should synchronize on them.
I've been struggling lately to find a way to deliver strings through a socket file. I'm planning to create a remote tool(client) to execute things based on the received message(server).
I've searched answers for my problem on google and i found some things and managed to understand things but I also got some problems (i'm new to programming, not yet in college).
I would appreciate any help in this matter
SocketService.java ---- class file = serverside
package socket;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
public class ServiceSocket {
static ServerSocket myService;
static Socket thesocket;
static Thread socketThread;
public static boolean socketRunning;
public static DataInputStream socketMessage;
public static void initialise(String localhost, int portNumber ){
// make a server socket//////
try {
myService = new ServerSocket(portNumber);
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
//////////////////////////////
}
public static void deploySocket(){
socketThread = new Thread() {
public void run(){
// making connection
System.out.println("VVaiting for connection...");
try {
thesocket = myService.accept();
System.out.println("Connection made");
socketRunning = true;
} catch (IOException e) {
e.printStackTrace();
}
////////////////////////////////////
try {
StartBrain();
} catch (IOException e1) {
e1.printStackTrace();
}
if(socketRunning = false) {
try {
thesocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
socketThread.start();
}
public static String getSocketMessage() throws IOException {
try {
socketMessage = new DataInputStream(thesocket.getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
boolean looprunning = true;
String message = null;
System.out.println("entering loop");
do {
try {
while (socketMessage.readUTF() != null) {
message = socketMessage.readUTF();
looprunning = false;
}
} catch (EOFException e) {
}
}while(looprunning);
System.out.println("Message received from UTF: " + message);
System.out.println("loop exited vvith message");
if(message == null) {
message = "no message";
}
return message;
}
public static void StartBrain() throws IOException {
System.out.println("socket brain started");
String BrainMessage = getSocketMessage();
if(BrainMessage == "command") {
System.out.println("Command EXECUTED HAHA");
} else if(BrainMessage == "taskschedule") {
System.out.println("task scheduled");
} else {
System.out.println("no command received");
}
}
Main.java ----- class file = serverside
package main;
import socket.ServiceSocket;
public class Main {
public static void main(String[] args) {
ServiceSocket.initialise("localhost", 3535);
ServiceSocket.deploySocket();
}
}
}
Main.java = CLIENT
package mainPackage;
import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;
public class Main {
private static Socket clientSocket;
public static void sendMessage(String message) throws IOException, InterruptedException {
DataOutputStream dOut = new DataOutputStream(Main.clientSocket.getOutputStream());
dOut.writeUTF(message);
dOut.flush();
dOut.close();
}
public static void main(String[] args) throws Exception {
// String modifiedSentence;
clientSocket = new Socket("localhost", 3535);
System.out.println("Initializing");
sendMessage("command");
boolean running = true;
while(running) {
TimeUnit.SECONDS.sleep(3);
sendMessage("taskschedule");
}
clientSocket.close();
}
}
main problem
do {
try {
while (socketMessage.readUTF() != null) {
message = socketMessage.readUTF();
looprunning = false;
}
} catch (EOFException e) {
}
}while(looprunning);
it doesn't read the string/UTF
It does read it, here:
while (socketMessage.readUTF() != null) {
and then throws it away as you're not assigning the return-value to a variable, and then tries to read another one, here:
message = socketMessage.readUTF();
but the one (first) message you send is already gone.
You have problem in
while (socketMessage.readUTF() != null) {
message = socketMessage.readUTF();
looprunning = false;
}
First call to method readUTF() will block thread and read UTF string from socket, but you discard this value and try read string second time.
If you replace socketMessage.readUTF() != null with looprunning server will log this messages:
VVaiting for connection...
Connection made
socket brain started
entering loop
Message received from UTF: command
loop exited vvith message
no command received
P.S.
Command is not recognized because use compare objects (string is object) with ==, but you must use equals.
public static void StartBrain() throws IOException {
System.out.println("socket brain started");
String BrainMessage = getSocketMessage();
if (BrainMessage.equals("command")) {
System.out.println("Command EXECUTED HAHA");
} else if (BrainMessage.equals("taskschedule")) {
System.out.println("task scheduled");
} else {
System.out.println("no command received");
}
}
Server log:
VVaiting for connection...
Connection made
socket brain started
entering loop
Message received from UTF: command
loop exited vvith message
Command EXECUTED HAHA
I want to capture an AXIS camera & stream it. I am quite new to RED5. I get the following error:
Exception in thread "main" java.lang.NullPointerException at
org.vikulin.rtmp.publisher.Publisher2.packetReceived(Publisher2.java:23)
at
org.red5.server.presentation.output.flv.FLVStream.dispatchEvent(FLVStream.java:243)
at
org.red5.server.presentation.output.flv.FLVStream.sendAVCDecoderConfig(FLVStream.java:162)
at
org.red5.server.presentation.output.flv.FLVStream.addEvent(FLVStream.java:76) at
org.red5.server.presentation.MediaPresentation.onMediaEvent(MediaPresentation.java:43)
at
org.red5.server.presentation.input.avp.codecs.H264.addPacket(H264.java:206)
at
org.red5.server.presentation.RTSPStream.onRTSPEvent(RTSPStream.java:100)
at
org.red5.server.net.rtsp.proxy.RtspTcp.setupAndPlay(RtspTcp.java:287)
at org.red5.server.presentation.RTSPStream.onSDP(RTSPStream.java:138)
at
org.red5.server.net.rtsp.proxy.RtspTcp.parseDescription(RtspTcp.java:128)
at org.red5.server.net.rtsp.proxy.RtspTcp.describe(RtspTcp.java:64)
at
org.red5.server.presentation.RTSPStream.startInput(RTSPStream.java:77)
at org.red5.server.presentation.RTSPStream.start(RTSPStream.java:82)
at org.vikulin.rtmp.publisher.Publisher2.main(Publisher2.java:49)
Here is the code:
import java.io.IOException;
import org.red5.server.api.stream.IBroadcastStream;
import org.red5.server.api.stream.IStreamListener;
import org.red5.server.api.stream.IStreamPacket;
import org.red5.server.net.rtmp.event.VideoData;
import org.red5.server.presentation.RTSPStream;
import org.red5.server.stream.message.RTMPMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Publisher2 implements IStreamListener {
PublishClient client;
#Override
public void packetReceived(IBroadcastStream arg0, IStreamPacket arg1) {
System.out.println("" + arg1);
VideoData data = new VideoData(arg1.getData());
RTMPMessage message = RTMPMessage.build(data);
try {
client.pushMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
Logger log = LoggerFactory.getLogger(Publisher2.class);
String publishName = "testb";
String host = "127.0.0.1";
int port = 1935;
String app = "live";
PublishClient client = new PublishClient();
client.setHost(host);
client.setPort(port);
client.setApp(app);
client.start(publishName, "live", null);
while (client.getState() != PublishClient.PUBLISHED) {
Thread.sleep(500);
}
Publisher2 test = new Publisher2();
final RTSPStream camera = new RTSPStream("192.168.254.115", 554,
"rtsp://192.168.254.115/axis-media/media.amp?videocodec=h264&videokeyframeinterval=30&fps=30");
camera.addStreamListener(test);
new Thread(new Runnable() {
#Override
public void run() {
camera.start();
}
}).start();
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
camera.stop();
try {//wait for write out.
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.stop();
}
}
If you have any idea please help me!
You declared a client variable in your main method, but in your packetReceived method, you reference the class variable. The class variable is still null at that point. So, possibly change this line:
PublishClient client = new PublishClient();
to this:
client = new PublishClient();
or pass the client in to your method, and remove variable declaration from your class.
I am using xjc to generate classes from xsd. The generation has to happen inside the java code. Right now I have done it like this:
Process child = Runtime.getRuntime().exec(command);
try {
System.out.println("waiting...");
child.waitFor();
System.out.println("waiting ended..");
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
The output for the above program is:
waiting...
I have to use the classes after they are generated. The problem here is that the subprocess never exits and the control is never back to the java program!
Is there a way to do this without getRuntime().exec() ?
You can actually use the driver class (com.sun.tools.xjc.Driver) behind the command line tool. This worked for me:
import com.sun.tools.xjc.BadCommandLineException;
import com.sun.tools.xjc.Driver;
import com.sun.tools.xjc.XJCListener;
import org.xml.sax.SAXParseException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Generator {
public static void main(String[] args) throws BadCommandLineException, IOException {
final String targetDir = "jaxb-files";
Path path = Paths.get(targetDir);
if(!Files.exists(path)) {
Files.createDirectories(path);
}
Driver.run(new String[]{"-d", targetDir,
"D:\\dev\\onepoint\\tui\\java\\xsdjsonschema\\src\\main\\xsd\\test.xsd"}, new XJCListener() {
#Override
public void error(SAXParseException e) {
printError(e, "ERROR");
}
#Override
public void fatalError(SAXParseException e) {
printError(e, "FATAL");
}
#Override
public void warning(SAXParseException e) {
printError(e, "WARN");
}
#Override
public void info(SAXParseException e) {
printError(e, "INFO");
}
private void printError(SAXParseException e, String level) {
System.err.printf("%s: SAX Parse exception", level);
e.printStackTrace();
}
});
}
}
try this
Process child = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(
new InputStreamReader(child.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}