Reputation: 3784
I'm trying to make a Java TCP client and a node.js TCP server talk together. This is my code at the moment :
The Java client
import java.net.; import java.io.;
public class Client2{
public static void main(String[] args) throws Exception{
Socket s = new Socket("192.168.1.35",8500);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("abcdefgh");
dos.close();
s.close();
}
}
the Node.js Server
var net = require('net'), server = net.createServer();
server.on('connection', function (client) {
console.log('Hello World !');
client.on('data', function(data) {
var message = data.toString('utf8');
console.log('***' + message +'***');
});
});
server.listen(8500);
This example will give this result back :
Hello World !
**abcdefgh***
but with this as input :
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
it gives this back :
Hello World !
***�abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz***
with this input :
qq32we3w87d 38s1d87s4df7s4d1+s2d7f+sfdsf4sà$àà3663%ç%&ç%&ç
it gives this back :
Hello World !
***@qq32we3w87d 38s1d87s4df7s4d1+s2d7f+sfdsf4sà$àà3663%ç%&ç%&ç***
tldr: Sometimes when logging the buffers, node adds characters (rectangles with numbers or ?) at the beginning or event cuts some characters at the start out.
- How can I log buffers and assign them to a variable the right way ?
Upvotes: 0
Views: 541
Reputation: 117
I'm not an expert on DataOutputStream, but if it really is adding extra characters, you should use something else.
When I did server stuff, I used BufferedReader and BufferedWriter. It looks like this:
Socket s = new Socket(<<WEB ADDRESS AS STRING>>,<<PORT NO AS INT>>);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//left out a bunch of lines. This is where you should read the lines
//of input (with an inner loop) and send stuff back
s.shutdownInput();
bw.flush();
s.shutdownOutput();
NOTE, IF YOU'RE GOING TO DEAL WITH LARGE PAGES, THIS COULD CAUSE A PROBLEM, AS THE BUFFEREDREADER AND BUFFEREDWRITER WILL FILL UP BEFORE YOU'RE READY. if this is a problem I'd look into the other Reader and Writer classes. They are quite plentiful, as I understand it, and one should suit your needs.
Upvotes: 1