So I am creating an application using sockets. And I have the client who sends a message and it passes to the server using writeObject(new String("Name|Message"));.
And I read the message in the server using readObject();
I am trying to pass this string object to an array. But I get [Ljava.lang.String;#6bb9ae1a.
Here is what I am trying:
ObjectInputStream saida = new ObjectInputStream(client.getInputStream());
String[] read = saida.readObject().toString().split("|");
System.out.println(read);
I tried also to make variables for each split:
String readm = read[1];
String readn = read[0];
But it returns me "" as the name and "A" as the message (?)
Ow, and the socket is working, because if I do (String) saida.readObject(); it returns me the normal string.
use like that :
saida.readObject().toString().split("\\|");
and then
String readm = read[1];
String readn = read[0];
Because pipe symbol is the special character and splitting special chars is different. And you cannot use systemoutprintln to print the string array.
Related
is some way to compare
String sentence = new String(receivePacket.getData());
with some string ?
I tried compare with
Arrays.equals(sentence.getBytes(),new String("Hello").getBytes();)
return false ...
I tried
if(sentence.equals("Hello"))
doesnt work too.
I think something is wrong with receivedPacket but data in packet are the same
like
'Hello' vs 'Hello'
System.out.println(sentence.getBytes()+ " vs " + "Hello".getBytes());
output -
[B#4f0e921d vs [B#459ad677
new String(packet.getData());
The problem is here. You're ignoring the length. It should be:
new String(packet.getData(), packet.getOffset(), packet.getLength());
I have a simple socket client written in netty.io and for data sending and receiving I use SimpleChannelInboundHandler. and in Initializer class I defined this:
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
but in this way I need every time put "\n" new line symbol at the end of string which I needn't. without this symbol I can't send or receive any string data. what is the solution use string data in netty without new line delimiter?
You can specify whatever delimiter you like, for instance
ByteBuf[] delimiters = new ByteBuf[] {
Unpooled.wrappedBuffer(new byte[] { '\r', '\n' }), // WINDOWS
Unpooled.wrappedBuffer(new byte[] { '\n' }), // UNIX / OSX
Unpooled.wrappedBuffer(new byte[] { '\r' }) // LEGACY MAC
};
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(MAXFRAMELENGTH, delimiters));
In this way, if you omit it, you can get rid of \n and replace with another character.
If you want to omit any delimiter, than I think you could use a FixedLengthFrameDecoder:
pipeline.addLast("framer", new FixedLengthFrameDecoder(yourFrameLength));
or a LengthFieldBasedFrameDecoder for more options.
I'm trying to get a very simple Client-Server system to work, where the Client will send a String over to the Server, and the server will then store that String into a file.
The client sends the string through:
//Other Code
sockStrm = new DataOutputStream (clientSocket.getOutputStream ());
//Other code
sockStrm.writeChars (line);
//Other code
And the Server receives the String with:
//Other code
strm = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
//Other code
stringLine = strm.readLine ();
//Other code
When I send the string STOP, the length of the String is 4 on the client side, and on the server side the length of the String is 9 and displays as STOP
I've tried to substring the received String on the Server side, without luck.
Any pointers on how to deal with this?
Use symmetric methods:
DataOutputStream sockStrm =...
sockStrm.writeUTF(str);
and
DataInputStream sockStrm = ...
String str = sockStrm.readUTF();
writeChars writes individual characters as two byte values. Readers follow the encoding to reconstruct the string from a sequence of bytes, which will definitely not be according to high-byte-low-byte for each character code. Hence you get some mish-mash of zero bytes with the original low-byte values so you still have a glimpse of the original string value.
Using \x00 to denote a NULL byte:
S-T-O-P => on the line: \x00-S-\x00-T-\x00-O-\x00-P => prints as STOP
Use a loop over the characters of the incoming string and display their integer values (str.charAt(i)) to see the above for yourself.
I would like to get data from InputStream() as a String eg. Hi, Start, Stop, etc.
My Code fragment is
byte[] buffer = new byte[1024];
inputStream.read(buffer);
My data is Command Sent from Bluetooth.
The above code fragment only get (eg. 2 if I sent Hi, 5 if sent Start), I would like to get back Normal String as the same from the Sender Side.
I found only converting way from String to InputStream.
any suggestion , I would like to appreciate!
finally, i can solve this!
inputStream.read(buffer); only return the int num of how many bytes is in the buffer and the data from the socket is stored in buffer. So, from the buffer you can make String
eg. String result = new String (buffer);
The simplest way is via the Apache common-io library:
String input = IOUtils.toString(inputStream);
See the javadoc for this method for more.
I'm trying to write simple code for server/client.
The server (in java) wait for string from client:
ServerSocket ss = new ServerSocket(4001);
Socket s = ss.accept() ;
DataInputStream dataStreamIn = new DataInputStream(s.getInputStream()) ;
byte buffer[] = new byte[100];
dataStreamIn.read(buffer);
if((new String(buffer)).equals("1"))
System.out.print("yes");//never printed
the client (objective-c) send string to server:
uint8_t buffer[1000] ={0};
sprintf((char*)buffer,"%s", "1");
NSInteger wrote = [self.networkStreamOut
write:buffer
maxLength:(uint8_t)strlen((char *)buffer)];
The problem is the buffer on server is indeed "1" BUT when I'm trying to compare with .equals() it return false!
EDIT:
When I'm tring to add to server this line:
System.out.println(Integer.valueOf(new String(buffer))) ;
I'm getting this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1
You should explicitly state what encoding you expect your incoming data to be in, on both the client and server side. This is especially important to do when communicating between different platforms/languages.
But, of course, that's not what your problem is - your string is getting created with a bunch of non-printing characters because you allocated it with the entire byte array:
byte[] buffer = new byte[100];
new String(buffer);
Presumably the buffer is not completely filled after you read data into it, and the defaulted zero values in it are getting converted in your string into non-printing characters. You can validate this by printing the length of the string you created, you will find it to be greater than 1.
You have two remedies - either trim() the String before comparing its value, or keep track of the number of actual bytes read and create a new byte array of the correct length (before creating your String).