Java socket not receiving exact message - java

Im sending a message from an android device to the server app in c#... i have successfully sent message from mobile device and received or server but a message from server is not being received in its original form on mobile device...
C# code for sending message
if (message == "Share_Screen")
{
string msg = "Go to java Socket in Android";
byte[] bfr = Encoding.ASCII.GetBytes(msg);
MessageBox.Show("No of bytes to be send are "+bfr.Length);
socket.Send(bfr);
}
Java Code for Sending and receiving single message
try
{
Socket socket = new Socket(ip,5353);
byte[] receiverBuffer = new byte[28];
byte[] buffer = "Share_Screen".getBytes();
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.write(buffer,0,buffer.length);
//sending successfully this message to c# socket
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
dataInputStream.read(receiverBuffer);
String msg = receiverBuffer.toString();
dataOutputStream.close();
dataInputStream.close();
socket.close();
return msg;
//expected message is " Go to java Socket in Android "
//received message is " |b#52a5395c "
}
catch (IOException e)
{
return "error";
}
message im receiving in android device is like "|b#52a5395c"

Related

Java client receiving message from NodeJS server via socket

So basically I'm trying to communicate between a Java client and a NodeJS server. Java sends a message via a socket, Node receives it using an event listener, then Node tries to send a response to Java. Something like "OK" because the message was received.
Java (in Main.java)
try {
Socket s = new Socket("localhost", 6666);
// Send a message to the server
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8);
out.write("test");
out.flush();
// Receive a message from the server
InputStream input = s.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
System.out.println(line);
} catch (Exception e) {
System.out.println(e);
}
NodeJS
var net = require('net');
var server = net.createServer(function (connection) {
console.log("Client connected");
connection.on('data', function (data) {
console.log('Request from', connection.remoteAddress, 'port', connection.remotePort);
console.log(data.toString())
connection.write("OK");
});
})
server.listen(6666, () => console.log(`Server is listening...`));
The server displays:
Server is listening...
Client connected
Request from ::ffff:127.0.0.1 port 65025
test
but the client is empty, it doesn't get server's response.
I can't figue out where the problem is. I found countless examples for two-way socket communications, but most of them between a client/server written both for Java/NodeJS. Their code was still similar with what I wrote, but doesn't work. Thanks a lot!

Java socket, client hangs when get input from server output

i have a socket in client that connects to an server to send and receive String, uses writeUTF() and readUTF() to read and write to socket, when i write a string from client to socket and read them on server then it's work. But when server receive string from socket and write "flag" to socket to read them on client then client hang at read line. Here is my code.
Server
public void run(){
DataInputStream input = null;
try{
output = new DataOutputStream(socket.getOutputStream());
input = new DataInputStream(socket.getInputStream());
while((true)&&(this.active)){
String receive = input.readUTF();
String[] str = receive.split("#");
if (str[0].equals("get_list")){
output.writeUTF("flag");
}
}
}catch(IOException ex){
}
Client
public void run(){
DataOutputStream output = null;
try{
output = new DataOutputStream(socket.getOutputStream());
DataInputStream input = new DataInputStream(socket.getInputStream());
output.writeUTF("get_list#");
String receive = input.readUTF(); //Hang at this line
System.out.println(receive);
} catch (IOException ex) {
}

UDP Sending and Receiving

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!

java.io.IOException: Connection reset by peer

I'm trying to manage a connection between my phone and another bluetooth device. I'm doing all this using java Android. This is the code I used for connecting the socket using my device:
First I find the Bluetooth device and I create the socket:
BluetoothDevice btNonin = null;
for (BluetoothDevice device : pairedDevices)
{
if (device.getName().contains("Nonin"))
{
// We found the device
exito = true;
try
{
// We create the socket
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
}
catch (Exception e)
{
Dialogs.showInfoDialog(NONIN_OFF, this);
}
}
}
Afther that I create the data bytes I want the remote bluetooth to receive using some code to convert ASCII to byte:
String[] parts = mensaje.split(" ");
String res = "";
if(parts != null && parts.length > 0)
{
for (String s : parts)
{
if (s.length() != 2)
break;
byte izq, der;
izq = (byte)char2ascii(s.charAt(0));
der = (byte)char2ascii(s.charAt(1));
byte aux2 = (byte)((izq << 4) + der);
res += (char)aux2;
}
}
And then I send the data to the bluetooth device:
// We send the data bytes
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeBytes(res);
dOut.flush();
Until here it works fine. It sends the data bytes to my device. But then I want to wait for any response from my device, and then I try this:
//Waiting for response
DataInputStream dIn = new DataInputStream(socket.getInputStream());
try
{
byte response = '\u0000';
while (dIn.readByte() == '\u0000')
{
response = dIn.readByte();
}
Dialogs.showInfoDialog("Response: " + response, this);
}
catch (Exception e)
{
Dialogs.showInfoDialog("No se ha recibido respuesta: " + e.toString(), this);
}
But then, on the line where I make dIn.readByte it shows the message Error:
java.io.IOException: Connection reset by peer
And I don't know why the connection is reset or what happens, as I can debug the line:
DataInputStream dIn = new DataInputStream(socket.getInputStream());
With no mistakes, so I guess the socket is still opened... What is happening here?
Thank you so much for your help!
There are several causes of this problem. The typical cause is that you have written to a connection which has already been closed by the peer. In other words, an application protocol error.
Also your exception handling needs work. If you get any IOException on a socket other than a timeout you must close it, it is dead.
Ok, I tried adding some wait() functions and it seems it works... As it was a problem between timeouts of reading and writing. I think this post should work...
remove the line dOut.flush(); this is causing the connection reset.

Can't get Java and C# to communicate through sockets

I've been trying to create a Java and C# app that would communicate together. In this case the user sends a String from the C# side, it should display on the Java console and echo back. Unfortunately, I have only been able to establish the connection, without being able to send or receive anything.
Java code snippet:
public CommunicationThreadHandler(Socket socket, CarList carList) {
this.socket = socket;
this.carList = carList;
try {
this.in = new DataInputStream(socket.getInputStream());
this.out = new DataOutputStream(socket.getOutputStream());
this.writer = new Writer(out);
} catch (IOException e) {
System.out.println("Exception when reading or receiving data!");
e.printStackTrace();
}
this.ip = socket.getRemoteSocketAddress().toString();
}
#Override
public void run() {
while (true) {
try {
Gson gson = new Gson();
String msgJson = in.readUTF();
String msg = gson.fromJson(msgJson,String.class);
System.out.println("Message from C# client: "+msg);
String reply = "Server echo: "+msg;
String replyJson = gson.toJson(reply);
out.writeUTF(replyJson);
if (msg.equals(Package.EXIT))
break;
} catch (IOException e) {
e.printStackTrace();
}
}
C# snippet:
public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
while (true)
{
Console.Write("Enter message to server: ");
string message = Console.ReadLine();
Console.WriteLine($"To be sent: {message}");
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(message);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
string msgFromServer = Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (msgFromServer.Equals("EXIT"))
break;
Console.WriteLine($"Server says: {msgFromServer}");
}
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
Your problem is that you're using DataInputStream/DataOutputStream in Java, which use a Java-specific, XDR-like datatype serialization protocol. You are not using that protocol at your C# side.
Switching to using the raw input/output stream should be sufficient (although very brittle). However, notice that as you are sending raw bytes from C#, it will be impossible to tell for the recipient when the message is complete. It would be better to send the number of bytes of the message, followed by the actual message (this is what DataInputStream/DataOutputStream does, but it comes with additional considerations that you would need to correctly implement in your C# side, for example readUTF/writeUTF use a 'modified UTF-8' format instead of normal UTF-8).
The problem right now, is that you send raw bytes from C#, the readUTF() method reads the first two bytes as length, and then tries to read a message of that length. For example if C# sends "Hello" (encoded as 0x48, 0x65, 0x6c, 0x6c, 0x6f), then the Java side will read 0x48, 0x65 ("He") as "message length is 18533" and then tries to read 18533 bytes, while the actual remaining bytes are only 3 (the "llo"). This causes the input to block waiting for the remaining 18530 bytes, which never arrive.

Categories