Python client write to Java's writeUTF method - java

I have the following code snippet for a Java server that can't be changed:
....
while(true){
try {
System.out.println("Will listen . . .");
instruction = this.dis.readUTF(); // Socket's dataInputStream
System.out.println("Got instruction: " + instruction);
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
....
} // end while(true)
And I have the following client code for python:
....
self.socket.send(b"GET~CARD\n")
print self.socket.recv(1024)
....
The problem that I'm facing is that I can get the client to send information to the server but the server won't stop listening, so it stays on the blocking call this.dis.readUTF();.
As you can see I tried using the \n character at the end of the string but it stays listening. Does anybody knows how to write from a python client to a java server using readUTF()?

Have a look at the docs for the readUTF function here
Primarily, this stands out
First, two bytes are read and used to construct an unsigned 16-bit
integer in exactly the manner of the readUnsignedShort method . This
integer value is called the UTF length and specifies the number of
additional bytes to be read. These bytes are then converted to
characters by considering them in groups. The length of each group is
computed from the value of the first byte of the group. The byte
following a group, if any, is the first byte of the next group.
Try something like this in your python code
import struct
message = u"GET~CARD\n"
size = len(message)
...
sock.send(struct.pack("!H", size))
sock.send(message)

Related

Send Data between client and server as a byte array

I am trying to send encrypted data between a client and server. Due to the RSA encryption its in Byte array form. This means I have had to change the way I send data. I curently cant get it working, Ill leave my method (sendMessage) below which is what handles the sending of the message, If anyone could tell me what I am doing wrong that would be great :)
public void sendMessage(byte[] msg){
if(msg.equals("null")){
}
else{
try{
ByteArrayOutputStream f = new ByteArrayOutputStream(CSocket.getOutputStream());
out = new PrintWriter(f);
out.write(msg);
countSend++;
}catch (IOException e){
System.out.println("ERROR");
}
}
}
Sorry should have clarified, essentially CSocket is a socket I have opend and I want to send msg through the socket. The issue I have specifically with this code is It says that: OutputStream can not be converted to int on the line where I creat the ByteArrayOutputStream object f and No suitable method found for write(byte[]) on the line out.write(msg);
Thanks for the clarification! Please see https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#write(byte%5B%5D,int,int)
The write method in ByteArrayOutputStream for byte[] needs two more arguments. Something like the following might work:
out.write(msg, 0, msg.length);
Please let me know if this is useful.
I think I fixed my issue now. Its probibably not the most efficient way of doing it but essentially I encode the byte array in a format that means I wont loose any data. This means I send it in this encoded format and then on the receving end I just simply decode it. Works so much better with print writer doing it this way.
OutputStream f = CSocket.getOutputStream();
out = new PrintWriter(f);
String encodedmsg = new String(msg, "ISO-8859-1"); // ISO-8859-1 is supposed to give every character a unique representation so I shouldent loose any data during encoding and decoding
out.write(encodedmsg);

golang Server with Java Client

I have a big problem....
We have a project on school and work as dou.
I write the go server and my partner the java client.
I have a problem that if he is sending something like: "Hello World" the golang server split this into "Hello" and "World"
See Picture
The Java Code:
public class DataController {
public String recieveDataFromServer(Socket socket) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (!bufferedReader.ready()) { }
String data = bufferedReader.readLine();
return data;
}
public void sendDataToServer(Socket socket, String data) throws Exception
{
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(data);
}
}
The go Code:
func handleRequest(conn net.Conn) {
request := make([]byte, 256)
for {
_, err := conn.Read(request)
if err != nil {
Error.Println(err.Error())
return
}
Info.Println("Message Received: " + string(request))
message := []byte(time.Now().String())
message = append(message, []byte(": ")...)
message = append(message, request...)
broadcast(message)
}
}
The broadcast function just do a conn.Write(msg) for all the connections.
Does anyone know that the problem is?
Edit: I found the problem. Java add after each word a \r\n. Then the go server think the message ended. We switch now to c#. its easier and work correct while writing with a bufferedWriter to a socket.
You maybe need send first the number of bytes to read and later the bytes to read with io.ReadFull function... of this way you are sure that read all the string...
ReadFull in go https://golang.org/pkg/io/https://golang.org/pkg/io/
ReadFully Java with DataInputStream : https://docs.oracle.com/javase/8/docs/api/
First read int with the number of bytes....
Later read bytes with io.ReadFull method...
NOTE : You need write the integers in bigendianess to java.
binary.Write(tx, binary.BigEndian, value)
My advice make the complex in go and read int and readFull bytes in java...
NOTE : You can only simple write bytes in both directions if you need send images or some similar...
Code to send and write bytes in Go
Code to send and write bytes in Java
I hope this help...
In this case i will suggest to use gRPC. here is the documentation
and here is gitrepo.
Use protobuf instead of JSON to define the contract of service.
So you can use this service for other clients as well which may be in any language.
and for implementing this you just need to extract your service contract and generate your contract in client respective language.
May be its little expensive in term of building but it will make your project reusable and definately you will learn something new.

Trying to write and read from the same com port, successful at writing, but failing at reading. Wat do?

I'm trying to get some data from the com port, the same one I'm writing data on, but it proves hard to read. I managed to find a simple code piece to read it, but now, I only read zeros. What could be the cause?
I'm sending my code below, with explanation of their intended usages.
private void ReadFromComPortActionPerformed(java.awt.event.ActionEvent evt) {
try {
String text = EmulatorInput.getText();
sendData(text, "COM4");
String out_Text = Arrays.toString(read());
EmulatorOutput.setText(out_Text);
System.out.println(out_Text);
} catch (IOException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
This is a JButton, method name and parameter has been created by NetBeans. Code firsts gets a text from the input panel as a string, sends it with a com port name, connects to that port, and opens input/output streams by it, then writes the string it took from the input panel to the OutputStream. Then, I create a new string, named out_Text and use read() method to read the data from port.
Here is the read method;
private byte[] read() throws IOException {
byte[] buffer = new byte[16];
int total = 0, read = 0;
while (total <= 16 && (read = input.read(buffer, total, 16-total)) > 0) {
total += read;
}
return buffer;
}
After the first method I posted uses read() to converge it into a string that I can print as a byte array, I end up with only a byte of zeros.
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
I'm very confused by this, because I'm sure I write to the port. I even monitored what I write, and can see that as I use the program to write data to the com port, the data it received increases.
If there is something that is unclear or if you need more of the code, please contact via comments.
Thank you kindly.
After several tries, I've tried the same operation with jSSC, and managed to write again. However, I was still not able to read. Then I noticed, that I was creating pairs of com ports. So, simply, I started to write to one port, and received the data from the other port of the pair. It worked like a charm. I'm not sure if the same idea is valid for rxtx libraries, but because jSSC's documents are descriptive, and because it's easy to use, I switched to it, and the way I did worked. You can find a detailed explanation of how I did below, without the code.
PreStep > I had COM6 and COM7 intact when I started this.
Step1 > Opened both ports via jSSC's methods. I constructed them as SerialPort, and then set their parameters (BaudRate, DataBits, etc.).
Step2 > I started to take inputs from console, and write them to the COM6. When I monitored the port, and the bytes in it, it was changing each time I sent an input.
Step3 > Each time I would press "Enter" to send the input, I'd invoke a reading method from COM7 object, and it would send a byte array to the console (Via Arrays.toString(byte[] array) method).
I don't know why I can't read from the same port as I write, but alas, my problem is solved. Thanks for your time to read this answer. If you have any questions, please post them under this one as a comment.

Writing data to serial port, sends wrong character

When monitoring data sent to device i get this:
http://i.stack.imgur.com/u0kIT.png
but i expect one character: F0 ð
public void WritingDataToPort() {
SerialPort port = new SerialPort("COM26");
try {
System.out.println(port.openPort());
port.setParams(9600, 8, 1, 0);
port.writeString((char)240+""));
port.closePort();
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
I completly don't know how to send this "ð" characater. Tried all ascii codes.
You can't just send the char (or UTF8) through the serial port. You have to convert it.
First get the length of the char in UTF-8, then get the bytes and send the bytes.
Getting the size of UTF-8: Getting the actual length of a UTF-8 encoded std::string?
Then send it one by one. On the other side you need something to assemble them back.
You could also consider using a better alternative to writing bytes directly to the port, such as http://code.google.com/p/java-simple-serial-connector/
You could try unicode. UTF-8 code.
http://www.fileformat.info/info/unicode/char/f0/index.htm
C/C++/Java source code "\u00F0"

Jsch: Is there way to send Control Character

I am using Jsch to connect sshd server and I am new in this area. I successfully send non-control character such as, a, b ...so-on. However, I need to send "Esc" key command (Control Character) to perform specific task. According to the link, I tried several ways (by passing "27", "0033", "0x1b", and "^[") but did not work.
I have found a link to use sshj. Is there way to send Control Character using Jsch?
Thanks M.F.H
How about following snippet?
byte[] esc = { (byte)0x1b };
out.write(esc);
out.flush();
JCTerm, which is using JSch, has following definitions,
byte[] ENTER = {(byte)0x0d};
byte[] UP = {(byte)0x1b, (byte)0x4f, (byte)0x41};
byte[] DOWN = {(byte)0x1b, (byte)0x4f, (byte)0x42};
byte[] RIGHT = {(byte)0x1b, (byte)0x4f, (byte)0x43};
byte[] LEFT = {(byte)0x1b, (byte)0x4f, (byte)0x44};
....
Thanks. I have figured out this issue a little different way. I am sending character to VT100 terminal using JSCH to perform specific tasks. In the code, all inputs are converted to array of byte but the ASCII control character cannot be sent as a array of byte to VT100 terminal. According to post, I have to send control character as ASCII code (INT). Such as, If VT100 terminal needs ESC command then 27 (INT) must be written in the SSH Session input stream. ESC's ASCII code is 27. (Before, I sent 27 as string and converted to array of byte.)

Categories

Resources