I'm finding a way to get an array, each component can have value between 0 and 255.
I'm using Android Studio and I received data from a socket. The following is my code.
try {
InetAddress IpAddress = InetAddress.getByName(remoteName);
myUpd_socket = new DatagramSocket(remotePort);
// Send connect message
String str = "connect request";
send_data = str.getBytes();
DatagramPacket send_packet = new DatagramPacket(send_data,str.length(), IpAddress, remotePort);
myUpd_socket.send(send_packet);
byte[] dataArray = new byte[1024];
DatagramPacket udp_packet = new DatagramPacket(dataArray,dataArray.length);
while (true) {
myUpd_socket.receive(udp_packet);
byte[] buff = new byte[udp_packet.getLength()];
System.arraycopy(dataArray,0,buff,0,buff.length);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I need to get the same data from the transmitter. There is no negative value in original data. But when I checked the received data, the buff has a lot of negative values. I made something wrong here.
I'm a newbie of Java and android. So I'm really grateful if someone can help me.
Thank.
Why not to use:
RECEIVE
Socket socket = ...
DataInputStream in = new DataInputStream(socket.getInputStream());
int length = in.readInt(); // read length of incoming message
if(length>0) {
byte[] message = new byte[length];
in.readFully(message, 0, message.length); // read the message
}
SEND
byte[] message = ...
Socket socket = ...
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeInt(message.length); // write length of the message
out.write(message); // write the message
bytes are signed in Java. If you want the unsigned value (as an int), use this: byteValue & 0xFF.
Related
I've looking into multiple ways to do this and nothing has helped/worked new to Java UDP packets.
My code for Android is started via a service and it runs on a new thread.
Code for waiting:
try {
int port = 58452;
// Create a socket to listen on the port.
DatagramSocket dsocket = new DatagramSocket(port);
// Create a buffer to read datagrams into. If a
// packet is larger than this buffer, the
// excess will simply be discarded!
byte[] buffer = new byte[2048];
// Create a packet to receive data into the buffer
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// Now loop forever, waiting to receive packets and printing them.
while (true) {
// Wait to receive a datagram
dsocket.receive(packet);
// Convert the contents to a string, and display them
String msg = new String(buffer, 0, packet.getLength());
System.out.println(packet.getAddress().getHostName() + ": "
+ msg);
// Reset the length of the packet before reusing it.
packet.setLength(buffer.length);
}
} catch (Exception e) {
System.err.println(e);
}
Code for sending:
try {
String host = "MY PHONES IP";
int port = 58452; //Random Port
byte[] message = "LAWL,LAWL,LAWL".getBytes();
// Get the internet address of the specified host
InetAddress address = InetAddress.getByName(host);
// Initialize a datagram packet with data and address
DatagramPacket packet = new DatagramPacket(message, message.length,
address, port);
// Create a datagram socket, send the packet through it, close it.
DatagramSocket dsocket = new DatagramSocket();
dsocket.send(packet);
dsocket.close();
System.out.println("Sent");
} catch (Exception e) {
System.err.println(e);
}
}
It sends fine but won't receive on Android. Please help!
Also my Logcat output: http://pastebin.com/Rfw5mSKV
Thanks
-Fusion
http://systembash.com/content/a-simple-java-udp-server-and-udp-client/
I used that to and it works! Thanks to /u/TarkLark or Reddit!
I'm trying to send an image that was taken by my camera in my application as a byte array. I convert the bitmap to byte array, then to Base64 string, then endcode that to a byte array and send. When I try to send it however I get an exception that my string is too long to send.
preparing to send through to socket:
if(currentChatPartner==null)
return;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
msg.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, 0);
sendThroughSocketImage(encoded, clientSocket, currentChatPartner.getIP(), currentChatPartner.getPort());
Sending through to socket:
byte[] decoded = null;
decoded = encoded.getBytes();
try
{
socket.send(new DatagramPacket(decoded, decoded.length, ip, port));
} catch (IOException e)
{
System.err.println("\nUnable to send message");
return false;
}
return true;
Sometimes it works, but most it doesn't :( Is there a reason for this?? Is there a way I could fix it or shorten the string that is to be sent??
By using DatagramPacket you're sending an UDP message that has a miximum length a little short of 64kb. Easy to get a message to long exception. You should send your data using TCP socket.
Plenty of examples online e.g.
http://systembash.com/content/a-simple-java-tcp-server-and-tcp-client/
With respect to your comments, an example of sending the byte array via client socket
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
int start=0;
int len=decoded.length;
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.write(array, start, len);
I am implementing a p2p application, in which nodes communicate by UDP packet. The packets read from InputStream are sometime not complete.
Here is my code:
...
protected String key;
protected Identifier messId; //Identifier hold a BigInteger
protected String range;
protected String concat;
....
public ReplicationMessage(DataInput in) throws IOException {
fromStream(in);
}
public void fromStream(DataInput in)
try {
super.fromStream(in);
int length=in.readInt();
byte[] data=new byte[length];
in.readFully(data);
concat = new String(data);
System.out.println("concat: "+concat);
messId = new Identifier(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public void toStream(DataOutput out) {
try {
super.toStream(out);
byte[] data = concat.getBytes();
out.writeInt(data.length);
out.write(data);
messId.toStream(out);
} catch (IOException e) {
e.printStackTrace();
}
}
the read packet sometime is complete, for example
concat: 179136678282544:140737488355328
but sometime is not complete, for example
concat: 179136678282544
concat: 179136678282544
concat: 179136678282544
Can any one tell me what the problem is?
Many thanks
Here are the code for sending/receiving the UDP packet
for sending:
private void sendMessage(int comm, Message message, InetAddress ip, int port)
throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
dout.writeInt(comm);
dout.writeByte(message.code());
message.toStream(dout);
dout.close();
byte[] data = bout.toByteArray();
if (data.length > DATAGRAM_BUFFER_SIZE) {
throw new IOException("Message too big, size="+data.length+
" bytes, max="+DATAGRAM_BUFFER_SIZE+" bytes");
}
DatagramPacket packet = new DatagramPacket(data, data.length, ip, port);
socket.send(packet);
}
For receiving the UDP packet
byte[] buffer = new byte[DATAGRAM_BUFFER_SIZE];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
The sending node and receiving node belonging to one machine. the Buffer receiving packet is set to 10*1024 bytes which is much larger than packet length
Here is code for turning incoming datapacket into stream
ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData(),
packet.getOffset(), packet.getLength());
DataInputStream din = new DataInputStream(bin);
int comm = din.readInt();
byte messCode = din.readByte();
Message message = factory.createMessage(messCode, din);
UDP does not deliver damaged or partial packets. Either you aren't sending all the data or you aren't unpacking it properly. You still haven't posted all the code concerned so it is not possible to say exactly where.
I try to send a integer array via datagram socket. What is the best way to accomplish this.
MY sending code is:
public void sendObj(Object obj) {
try{
byteArr = new ByteArrayOutputStream();
objOut = new ObjectOutputStream(byteArr);
objOut.writeObject(obj);
byte[] b = byteArr.toByteArray();
DatagramPacket dgram = new DatagramPacket(b, b.length, InetAddress.getByName("230.0.0.1"), 4446); // multicast
socket.send(dgram);
System.out.println("Package is sent!");
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
And receiving code is:
byte[] b = new byte[65535];
ByteArrayInputStream b_in = new ByteArrayInputStream(b);
DatagramPacket dgram = new DatagramPacket(b, b.length);
socket.receive(dgram); // blocks
ObjectInputStream o_in = new ObjectInputStream(b_in);
Object o = o_in.readObject();
dgram.setLength(b.length); // must reset length field!
b_in.reset(); //
However when I receive it gives StreamException for unknown header value 00000
We solved that problem by a basic changes. We used a string like "100200300..." to symbolize the array by separating element with two 0' so in that way we did not use ArrayList.
You have to use getbyte() method to get the bytes and the put these bytes into a datagram packet instance and then pass it to the client or send it...
Use
arrayName.getBytes(); /// save this into some byte[] temp = new byte[size];
and make a datagram packet and put its argumnets and send it
i am making a program that sends a string from a Java client to a C server using WinSock2. I am using DataOutputStream to send the data through the socket.
The C server, acknowledges the bytes received, but when i try accessing the data, nothing is displayed.
SERVER
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("10.40.0.86", 2007);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
//dataOutputStream.writeUTF("How are you doing let us see what is the maximum possible length that can be supported by the protocal");
String line = "hey";
dataOutputStream.writeUTF(line);
dataOutputStream.flush();
//System.out.println(dataInputStream.readLine());
System.out.println((String)dataInputStream.readLine().replaceAll("[^0-9]",""));
//System.out.println(dataInputStream.readInt());
//System.out.println(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CLIENT
if (socket_type != SOCK_DGRAM)
{
retval = recv(msgsock, Buffer, sizeof(Buffer), 0);
printf("Server: Received datagram from %s\n", inet_ntoa(from.sin_addr));
}
output
Server: Received 5 bytes, data "" from client
BUFFER :
Server: Echoing the same data back to client...
BUFFER :
Server: send() is OK.
Your C code needs to understand the data format written by writeUTF() (see the Javadoc), or else more simply you need to use write(char[]) or write(byte[]) at the Java end.
Here is how I solved this :-)
dataOutputStream.write(line.getBytes());
Or to be more specific here is my code:
out.write(("Hello from " + client.getLocalSocketAddress()).getBytes());