Client IP address using emulator - sockets

I am currently writing this code for my client and server,
and I want to test it out using my emulator, but I'm stuck.
is this the correct IP address that I should be using?
socket = new Socket("10.0.2.2", 6000);
If i want to use my phone to test this out, what ip address should i be using?
thanks.

if you want to send messages between server/client, here is a sample code that i have made before.
please refer to the code below and feel free to comment!
also, that is the correct ip address to use when using emulator for simulation.
in addition, don't forget to change your permission to "android.permission.INTERNET" in your manifesto.
=================================myClient==================================
package com.example.myclient;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Manifest --> uses permission --> "android.permission.INTERNET" */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
class MyThread extends Thread {
#Override
public void run() {
super.run();
Log.d("client", "thread is running...");
String str = "Do you want to eat hamburger?";
Socket socket;
try {
socket = new Socket("10.0.2.2", 6000);
ObjectOutputStream out = new ObjectOutputStream(socket
.getOutputStream());
ObjectInputStream in = new ObjectInputStream(
socket.getInputStream());
out.writeObject(str);
String rcv = (String) in.readObject();
Log.d("client", "Server :" + rcv);
out.close();
in.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MyThread t = new MyThread();
t.start();
}
});
}
}
============================MyServer========================================
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket server = new ServerSocket(6000);
System.out.println("waiting.....");
while (true) {
Socket socket = server.accept();
System.out.println("a client has connected...");
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
ObjectInputStream objIn = new ObjectInputStream(in);
ObjectOutputStream objOut = new ObjectOutputStream(out);
String str = (String) objIn.readObject();
System.out.println("client : " + str);
objOut.writeObject("No, I'm on a diet!!!");
objIn.close();
objOut.close();
socket.close();
}
}
}

10.0.2.2 will be the correct IP you are using emulator. 127.0.0.1 will be the IP if you are developing on the machine(client and server on same machine). As you said you want to test it in your mobile run the following code and you will get your IP(it will also work if you are on computer):
public class net
{
net() throws UnknownHostException
{
InetAddress ia=InetAddress.getLocalHost();
System.out.println(ia);
ia=InetAddress.getByName("local host");
System.out.println(ia);
}
public static void main(String args[])throws UnknownHostException
{
net a=new net();
}
}

Related

The tcp server socket handler don't waiting for the result of the vertical and just close the socket.How to control it?

I'm writing a simple tcp server for short connection.
I have two vertical.
One handling the tcp request, get the eventBus and send the message to it.
Another vertical just consume and reply it.
The question is.Tcp client can't receive the result.I know the eventBus.request() is async.But don't know how to control it,just let the socket waiting for the result.
main
package org.example;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
public class Application {
public static void main(String[] args) {
VertxOptions options = new VertxOptions();
options.setEventLoopPoolSize(1);
Vertx vertx = Vertx.vertx(options);
DeploymentOptions ruleOptions = new DeploymentOptions();
ruleOptions.setWorker(true);
ruleOptions.setInstances(1);
vertx.deployVerticle("org.example.RuleVertical", ruleOptions);
DeploymentOptions serverOptions = new DeploymentOptions();
serverOptions.setInstances(1);
vertx.deployVerticle("org.example.ServerVertical", serverOptions);
}
}
server vertical
package org.example;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.net.NetServer;
public class ServerVertical extends AbstractVerticle {
#Override
public void start() throws Exception {
EventBus eventBus = vertx.eventBus();
NetServer netServer = vertx.createNetServer();
netServer.connectHandler(socket -> {
socket.handler(buffer -> {
eventBus.request("message.id", buffer.toString(), reply -> {
System.out.println("Server reply: " + reply.result().body());
socket.write(reply.result().body().toString()).onFailure(event -> event.printStackTrace());
});
});
});
netServer.listen(1234);
}
}
rule vertical
package org.example;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
public class RuleVertical extends AbstractVerticle {
#Override
public void start() throws Exception {
EventBus eventBus = vertx.eventBus();
eventBus.consumer("message.id", message -> {
try {
Thread.sleep(2000);
message.reply("hello");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
client
package org.example;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 1234);
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
System.out.println("Request: 1234");
printWriter.write("1234");
printWriter.flush();
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
System.out.println("Response: " + sb);
reader.close();
printWriter.close();
inputStream.close();
outputStream.close();
socket.close();
}
}
Server log
Server reply: hello
io.netty.channel.StacklessClosedChannelException
at io.netty.channel.AbstractChannel$AbstractUnsafe.write(Object, ChannelPromise)(Unknown Source)
Client log
Request: 1234
Response:

can Flink receive http requests as datasource?

Flink can read a socket stream, can it read http requests? how?
// socket example
DataStream<XXX> socketStream = env
.socketTextStream("localhost", 9999)
.map(...);
There's an open JIRA ticket for creating an HTTP sink connector for Flink, but I've seen no discussion about creating a source connector.
Moreover, it's not clear this is a good idea. Flink's approach to fault tolerance requires sources that can be rewound and replayed, so it works best with input sources that behave like message queues. I would suggest buffering the incoming http requests in a distributed log.
For an example, look at how DriveTribe uses Flink to power their website on the data Artisans blog and on YouTube.
I write one custom http source. please ref OneHourHttpTextStreamFunction. you need create a fat jar to include apache httpserver classes if you want run my code.
package org.apache.flink.streaming.examples.http;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.examples.socket.SocketWindowWordCount.WordWithCount;
import org.apache.flink.util.Collector;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.bootstrap.HttpServer;
import org.apache.http.impl.bootstrap.ServerBootstrap;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
public class HttpRequestCount {
public static void main(String[] args) throws Exception {
// the host and the port to connect to
final String path;
final int port;
try {
final ParameterTool params = ParameterTool.fromArgs(args);
path = params.has("path") ? params.get("path") : "*";
port = params.getInt("port");
} catch (Exception e) {
System.err.println("No port specified. Please run 'SocketWindowWordCount "
+ "--path <hostname> --port <port>', where path (* by default) "
+ "and port is the address of the text server");
System.err.println("To start a simple text server, run 'netcat -l <port>' and "
+ "type the input text into the command line");
return;
}
// get the execution environment
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// get input data by connecting to the socket
DataStream<String> text = env.addSource(new OneHourHttpTextStreamFunction(path, port));
// parse the data, group it, window it, and aggregate the counts
DataStream<WordWithCount> windowCounts = text
.flatMap(new FlatMapFunction<String, WordWithCount>() {
#Override
public void flatMap(String value, Collector<WordWithCount> out) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (String word : value.split("\\s")) {
out.collect(new WordWithCount(word, 1L));
}
}
})
.keyBy("word").timeWindow(Time.seconds(5))
.reduce(new ReduceFunction<WordWithCount>() {
#Override
public WordWithCount reduce(WordWithCount a, WordWithCount b) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new WordWithCount(a.word, a.count + b.count);
}
});
// print the results with a single thread, rather than in parallel
windowCounts.print().setParallelism(1);
env.execute("Http Request Count");
}
}
class OneHourHttpTextStreamFunction implements SourceFunction<String> {
private static final long serialVersionUID = 1L;
private final String path;
private final int port;
private transient HttpServer server;
public OneHourHttpTextStreamFunction(String path, int port) {
checkArgument(port > 0 && port < 65536, "port is out of range");
this.path = checkNotNull(path, "path must not be null");
this.port = port;
}
#Override
public void run(SourceContext<String> ctx) throws Exception {
server = ServerBootstrap.bootstrap().setListenerPort(port).registerHandler(path, new HttpRequestHandler(){
#Override
public void handle(HttpRequest req, HttpResponse rep, HttpContext context) throws HttpException, IOException {
ctx.collect(req.getRequestLine().getUri());
rep.setStatusCode(200);
rep.setEntity(new StringEntity("OK"));
}
}).create();
server.start();
server.awaitTermination(1, TimeUnit.HOURS);
}
#Override
public void cancel() {
server.stop();
}
}
Leave you comment, if you want the demo jar.

getting variables from other files in the project (like from main class and from other .class file) [duplicate]

This question already has answers here:
Passing Parameters JavaFX FXML
(10 answers)
Closed 5 years ago.
EDIT: Someone marked this as duplicate. I've read through the other question several times but I don't really understand how I can apply this to my program. It would be really nice if someone could help me in this specific context as I don't have much knowledge about Java yet. A short starting point would maybe even help me out. My question has nothing to do with a popup.
I have a problem. I don't wanna put the server code into the initialize() method of FXMLController. Instead I put the server start code into the start() method of MainApp and created a RemoteReader class. But how do I get the in and output stream variables from RemoteReader or MainApp into the FXMLController class? I'm using SceneBuilder.
Code:
FXMLController.java:
package de.freakyonline.ucone;
import de.freakyonline.ucone.Player;
import de.freakyonline.ucone.PlayerList;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Tab;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.InputMethodEvent;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class FXMLController {
#FXML
private ResourceBundle resources;
#FXML
private URL location;
#FXML
private BorderPane borderPane;
#FXML
private TableView<Player> playerTable;
final Tooltip playerTableToolTip = new Tooltip("Rightclick for more options ...");
#FXML
private TableColumn<Player, String> nickColumn;
#FXML
private TableColumn<Player, String> groupColumn;
#FXML
private TableColumn<Player, String> yearOfBirthColumn;
#FXML
private TableColumn<Player, Integer> ageColumn;
#FXML
private TableColumn<Player, String> genderColumn;
#FXML
private TableColumn<Player, String> lastQuitColumn;
#FXML
private Tab consoleOneTab;
#FXML
private MenuBar mainMenuBar;
#FXML
private TextArea consoleOneTextArea;
#FXML
private TextField consoleOneTextField;
#FXML
void handleConsoleOneAction(ActionEvent event) {
switch(consoleOneTextField.getText().toLowerCase()) {
case "freaky":
consoleOneTextArea.appendText("Freaky rulez! :D\n");
break;
case "ky3ak":
consoleOneTextArea.appendText("Ky3ak rulez! :D\n");
break;
case "testserver":
consoleOneTextArea.appendText("Sending an object ...");
// PROBLEM: I don't know how I can get the out variable of remote (RemoteReader) to here.
remote.out.writeObject(new Player("freakyy85","Owner","1810",31,"m","missing..."));
case "help":
consoleOneTextArea.appendText("This console is mainly to log stuff which is done by the program to the user, so they can see what's going on.");
break;
default: consoleOneTextArea.appendText("Unknown Command\n");
}
consoleOneTextField.clear();
}
#FXML
void handleConsoleOneTabSelected(Event event) {
consoleOneTextField.requestFocus();
}
#FXML
void handleFileClose(ActionEvent event) {
Platform.exit();
}
#FXML
void handleHelpAbout(ActionEvent event) {
Stage haStage = new Stage();
haStage.setTitle("Help --> About");
Label aboutText = new Label("UCOne by freakyy85\nInitially developed for Ky3ak and UnityCraft");
aboutText.setPadding(new Insets(20));
haStage.setScene(new Scene(new StackPane(aboutText)));
haStage.initOwner(borderPane.getScene().getWindow());
haStage.initModality(Modality.WINDOW_MODAL);
haStage.show();
}
#FXML
void handlePlayerEditCommit(TableColumn.CellEditEvent<Player, String> event) {
System.out.println(event.getRowValue().toString());
}
#FXML
void handleTextChanged(InputMethodEvent event) {
}
#FXML
private void handlePTContextMenuRequest(ContextMenuEvent event) {
System.out.println("Target: " + event.getTarget().toString());
System.out.println("Source: " + event.getSource().toString());
final ContextMenu playerTableContextMenu = new ContextMenu();
MenuItem testMenuItem = new MenuItem("Test");
testMenuItem.setOnAction( e -> consoleOneTextArea.appendText("Used ContextMenu in Playertable, here: " + event.getTarget().toString()));
MenuItem colorizeFont = new MenuItem("Colorize Font");
colorizeFont.setOnAction( e -> consoleOneTextArea.appendText("PickResult: " + event.getPickResult().toString()));
MenuItem makeLocalNotes = new MenuItem("Local Player Notes");
makeLocalNotes.setOnAction( (e) -> {
Stage plnStage = new Stage();
plnStage.setTitle("(nickHere) - PlayerLocalNotesEditor");
HTMLEditor playerLocalNotes = new HTMLEditor();
plnStage.setScene(new Scene(new StackPane(playerLocalNotes)));
plnStage.initOwner(borderPane.getScene().getWindow());
plnStage.initModality(Modality.WINDOW_MODAL);
plnStage.show();
});
playerTableContextMenu.getItems().add(testMenuItem);
playerTableContextMenu.getItems().add(colorizeFont);
playerTableContextMenu.getItems().add(makeLocalNotes);
playerTableContextMenu.show(borderPane.getScene().getWindow(),event.getScreenX(),event.getScreenY());
}
#FXML
void initialize() {
assert nickColumn != null : "fx:id=\"nickColumn\" was not injected: check your FXML file 'Scene.fxml'.";
assert groupColumn != null : "fx:id=\"groupColumn\" was not injected: check your FXML file 'Scene.fxml'.";
PlayerList playerList = new PlayerList();
playerTable.setItems(playerList.playerList);
nickColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("nick"));
groupColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("group"));
yearOfBirthColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("yearOfBirth"));
yearOfBirthColumn.setCellFactory(TextFieldTableCell.forTableColumn());
ageColumn.setCellValueFactory(new PropertyValueFactory<Player,Integer>("age"));
genderColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("gender"));
genderColumn.setCellFactory(TextFieldTableCell.forTableColumn());
lastQuitColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("lastQuit"));
playerTable.setTooltip(playerTableToolTip);
}
}
MainApp.java:
package de.freakyonline.ucone;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MainApp extends Application {
String ver = "v0.1-SNAPSHOT";
ObjectOutputStream out;
ObjectInputStream in;
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));
// Connect to Server
try {
Socket sock = new Socket("unitycraft.de", 2009);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
// Listen for remote stuff comming in ...
Thread remote = new Thread(new RemoteReader(in,out,sock));
remote.start();
} catch (Exception ex) { ex.printStackTrace(); }
Scene scene = new Scene(root);
scene.getStylesheets().add("/styles/Styles.css");
stage.setTitle("UCOne - The UnityCraft Staff Tool " + ver);
stage.setScene(scene);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
RemoteReader.java:
package de.freakyonline.ucone;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
/**
*
* #author uwe
*/
public class RemoteReader implements Runnable {
Object obj = null;
ObjectInputStream in;
ObjectOutputStream out;
Socket sock;
public RemoteReader (ObjectInputStream in, ObjectOutputStream out, Socket sock) {
this.in = in;
this.out = out;
this.sock = sock;
}
public void run() {
try {
while((obj=in.readObject()) != null)
System.out.println("Got object from server ...");
} catch (Exception ex) { ex.printStackTrace(); }
}
}
Btw, I'm currently learning. ;)
I got it working. I changed the main class to this:
public class MainApp extends Application {
String ver = "v0.1-SNAPSHOT";
ObjectOutputStream out;
ObjectInputStream in;
Socket sock;
Thread remote;
#Override
public void start(Stage stage) throws Exception {
FXMLLoader root = new FXMLLoader(
getClass().getResource("/fxml/Scene.fxml")
);
// Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));
// Connect to Server
try {
Socket sock = new Socket("unitycraft.de", 2009);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
// Listen for remote stuff comming in ...
Thread remote = new Thread(new RemoteReader(in,out,sock));
remote.start();
} catch (Exception ex) { ex.printStackTrace(); }
Scene scene = new Scene(root.load());
scene.getStylesheets().add("/styles/Styles.css");
FXMLController controller = root.<FXMLController>getController();
controller.initData(in,out,sock);
// Connect to Server
try {
Socket sock = new Socket("unitycraft.de", 2009);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
// Listen for remote stuff comming in ...
remote = new Thread(new RemoteReader(in,out,sock,controller.));
remote.start();
} catch (Exception ex) { ex.printStackTrace(); }
stage.setTitle("UCOne - The UnityCraft Staff Tool " + ver);
stage.setScene(scene);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
And I added in FXMLController this method, plus the declaration of the class fields (in,out,sock):
void initData(ObjectInputStream in, ObjectOutputStream out, Socket sock) {
this.in = in;
this.out = out;
this.sock = sock;
}
Now I can access the output stream from within FXMLController. But now I can't access the textarea from within RemoteReader.java. I started a new question. ;)

Raspberry PI Tomcat7 and Serial Port Communication using ISO8859-7

I am trying to relay a message from a Servlet to COM in raspberry pi on Tomcat 7.
I am using null cable between raspberry and my PCs to test.
I am using jssc API (Java Simple Serial Connector) for serial communication.
Raspberry pi is using JDK 1.8.0_65.
I am getting the message in UTF8 and I should output it in ISO8859-7.
Since UTF8 is a superset of ISO8859-7, the app that calls the servlet ensures all characters sent are legitimate for ISO8859-7.
My code:
package com.test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(value = "/Relay", name = "Relay")
public class Relay extends HttpServlet {
static Logger app = null;
static {
app = Logger.getLogger("com.test.app");
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) {
try {
request.setCharacterEncoding("ISO-8859-7");;
response.setCharacterEncoding("ISO-8859-7");
//request.setCharacterEncoding("UTF-8");
//response.setCharacterEncoding("UTF-8")
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String message = request.getParameter("message");
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", message);
String[] portNames = SerialPortList.getPortNames();
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", portNames.length+"");
for(int i = 0; i < portNames.length; i++){
applogp(Level.INFO, this.getClass().getCanonicalName(),"APP", portNames[i]);
byte[] msg = new byte[1024];
msg = message.getBytes("ISO-8859-7");
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88597charset = Charset.forName("ISO-8859-7");
ByteBuffer inputBuffer = ByteBuffer.wrap(message.getBytes());
CharBuffer data = utf8charset.decode(inputBuffer);
ByteBuffer outputBuffer = iso88597charset.encode(data);
byte[] outputData = outputBuffer.array();
byte[] b1 = message.getBytes();
byte[] b2 = message.getBytes(Charset.forName("ISO-8859-7"));
byte[] b3 = message.getBytes(StandardCharsets.ISO_8859_1);
SerialPort serialPort = new SerialPort((portNames[i]));
try {
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
serialPort.writeBytes(msg);
serialPort.writeBytes(message.getBytes());
serialPort.writeBytes(outputData);
serialPort.writeBytes(b1);
serialPort.writeBytes(b2);
serialPort.writeBytes(b3);
serialPort.closePort();
} catch (SerialPortException ex) {
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", ex.getMessage());
out.write("NOK");
out.close();
}
}
out.write("OK");
out.close();
} catch (IOException e) {
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", e.getMessage());
}
}
private static final long serialVersionUID = 1L;
}
The problem is that when I am testing I do not get valid output in putty.
putty output
I have configured putty to display ISO8859-7 characters.
Any for changes ?
What am I missing ?
Thanks in advance.
I tried to divide the problem by producing the following code:
import java.io.UnsupportedEncodingException;
import jssc.SerialPort;
import jssc.SerialPortException;
public class SerialTest {
public static void main(String[] args) {
String message = "message μήνυμα";
if ( sendTextOnCom(message) ) {
System.out.println("SUCCESS MESSAGE SENT");
}
else{
System.out.println("FAIL MESSAGE NOT SENT");
}
}
private static boolean sendTextOnCom(String message) {
boolean isOverlaid = false;
SerialPort com = null;
try {
String comNo = "COM1"; // String comNo="/dev/ttyUSB0"; //when used in Raspberry
com = new SerialPort(comNo);
com.openPort();
com.setParams(9600, 8, 1, 0);
com.writeString(message);
com.writeBytes(message.getBytes("ISO-8859-7"));
com.closePort();
isOverlaid = true;
}
catch (SerialPortException ex) {
System.out.println("[ERROR] COM ERROR SENDING MESSAGE");
isOverlaid = false;
try {
com.closePort();
} catch (SerialPortException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isOverlaid;
}
}
The code is working normally in Windows 7 64bit and it is producing output in putty with the right characters.
When I compile and run the same code in raspberry PI the output in putty is not showing the valid characters.
I tend to think that it's a raspberry PI configuration issue.

Passing BufferedReader as a parameter of a constructor of a class

I have set up a network and I've set up the reading and writing stream to a socket as so:
//Set up socket reads and writes
final BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
final PrintWriter out = new PrintWriter(
client.getOutputStream(), true);
I wanted to pass the two variables, 'in' and 'out', as parameters of another class' constructor. This is how it looks in the other class
BufferedReader in;
PrintWriter out;
public ClientThread(BufferedReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
I then wanted to use those class variables to write to the output stream of the same socket like this (the class implements Runnable):
public void run() {
while (true) {
try {
String userCommand = in.readLine();
} catch (IOException e) {
// Die if something goes wrong.
System.err.println(e.toString());
System.exit(1);
}
}
}
However, whenever the code gets to this point, I get a SocketException:
java.net.SocketException: Socket closed
How can I fix this? I want to separate the setting up of the server and the socket from the processing of any commands given by the client.
EDIT: Here's what the BufferedRead gets the input from
//create server socket
ServerSocket server = new ServerSocket(portNum);
// Accept a client if it appears
Socket client = server.accept();
EDIT 2: I used these three files:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
//Change the socket if it doesn't work
Socket sock = new Socket("localhost", 5920);
//keyboard
final BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
//input from socket
final BufferedReader in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
//writer to socket
final PrintWriter out = new PrintWriter(
sock.getOutputStream(), true);
//new thread for incoming messages
(new Thread(){
#Override
public void run() {
String serverMessage;
try {
while ((serverMessage = in.readLine()) != null) {
System.out.println(serverMessage);
}
} catch (IOException e) {
System.err.println("Something went wrong whilst trying "
+ "to retrieve a message from the server");
System.exit(-1);
}
}
}).start();
//new thread for outgoing messages
(new Thread(){
#Override
public void run() {
String clientMessage;
try {
while ((clientMessage = stdin.readLine()) != null) {
out.println(clientMessage);
}
} catch (IOException e) {
System.err.println("Something went wrong whilst trying "
+ "to send a message to the server.");
System.exit(-1);
}
}
}).start();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5920);
Socket client = server.accept();
//Set up socket reads and writes
final BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
final PrintWriter out = new PrintWriter(
client.getOutputStream(), true);
new Thread(new ClassWithParam(in, out)).start();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
public class ClassWithParam implements Runnable {
BufferedReader in;
PrintWriter out;
public ClassWithParam(BufferedReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
#Override
public void run() {
while (true) {
try {
System.out.println("HERE");
String userCommand = in.readLine();
System.out.println("HERE2");
} catch (IOException e) {
// Die if something goes wrong.
System.err.println(e.toString());
System.exit(1);
}
}
}
}
And now it works. Don't know what happened. Will proceed to bang head against wall. Thanks.
For some reason there's no problem now. The code (I recreated) which I used, which now works, is in the description.