Java Socket readLine() infinite, ends only if php script times out - java

I want to send a message with socket to an java server and it should response.
InputStreamReader inputStream = new InputStreamReader(server.getInputStream());
BufferedReader input = new BufferedReader(inputStream);
String clientSentence = input.readLine();
System.out.println(clientSentence);
This infinite, so I can't send a response to my php socket connection.
PHP:
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
$st="testSalt,broadcast";
$length = strlen($st);
socket_write($socket, $st, $length);
$resp = socket_read($socket, 1024);

Terminate strings from the PHP socket with a newline character to match the readLine statement of the Java server
$st = "testSalt,broadcast\n";

I don't know much about PHP, but it looks to me that if you send the contents of $st as-is, there won't be any newline character for the Java socket to read, and thus the input.readLine() call will hang until the Socket closes.

Related

Socket doesn't send data until it is closed

i have a simple application which create a socket between java(server) and python(client).
The main function of the python code is to take data from user and send it to the server(java code)
here's the python code
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 5000))
while True:
data = input("Enter data to send : ")
if(data == 'q'):
break
client_socket.sendall(data.encode('utf-8'))
client_socket.close()
and here's the java code
String fromclient;
ServerSocket Server = new ServerSocket (5000);
while(true)
{
Socket connected = Server.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
fromclient = inFromClient.readLine();
if ( fromclient.equals("q") ){
connected.close();
break;
}else {
System.out.println(fromclient);
}
}
when I write any text and click Enter, nothing goes to java code and nothing printed to the console, but when i send 'q' from python, the python code closed and all the data i wrote are now printed in java console.
I have no idea what is the reason of this, and how i can fix it.
The Java code waits for a line-break, but the Python part does not send one (input provides no line-break in the string it returns).
Try
client_socket.sendall((data+'\n').encode('utf-8'))
As #Kayaman suggests, the accept is in a wrong place (and also is the BufferedReader).
Socket connected = Server.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
while(true)
{
fromclient = inFromClient.readLine();
would be a better order.
Also, Python client does not send the 'q' in its current form. So the if with the fromclient.equals("q") will not close the socket, the code will just die on the next readLine() instead. Re-order the Python part too:
data = input("Enter data to send : ")
client_socket.sendall((data+'\n').encode('utf-8'))
if(data == 'q'):
break

Communication Java(Client) with Python(Server)

I am doing a simple Java Client application which should communicate with Python Server. I can easily send a string to Python Server and print it in console, but when i'm trying to use received string in IFs it never get into IF statement even if it should.
Here is Java Client send msg code
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
if(msgToServer != null){
dataOutputStream.writeUTF("UP");
}
System.out.println(dataInputStream.readLine());
And Python Server code:
import socket
HOST = ''
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
print 'Socket now listening'
conn, addr = s.accept()
print 'Connected to: ' + addr[0] + ':' + str(addr[1])
data = conn.recv(1024)
if data == "UP":
conn.sendall('Works')
else:
conn.sendall('Does not work')
conn.close()
s.close()
print data
So when i send to Python Server "UP" it should send back to Java Client "Works", but i reveive "Does not work" and in Python Server the output data is: "UP"
Why it isn't go into if statement?
The JavaDoc of DataOutputStream#writeUTF(...) says:
First, two bytes are written to the output stream as if by the
writeShort method giving the number of bytes to follow
In you python code your data value will be prefixed with two bytes for the length of the string to follow.

PHP socket sends data but Java socket is not receiving

I'm trying to transfer simple message between PHP socket and JAVA socket. The php socket successfully sends the data and is waiting for Java servers response. But on the other hand Java server's socket is still waiting for the message from PHP.
Here is the Java Code:
ServerSocket s = new ServerSocket(4280);
Socket sock = s.accept();
System.out.println("Connected");
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
System.out.println("Reading");
String str = br.readLine();
System.out.println("Writing");
bw.write(str);
Output:
Connected
Reading
Here's the PHP code:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, "localhost", 4280);
socket_write($socket, "Hello");
echo socket_read($socket, 10);
socket_write($socket, "Lelo");
echo socket_read($socket, 10);
Output:
Browser: waiting for localhost
Two things that can usually cause a problem:
Java is utilizing the readLine() method but your not sending a linefeed and return in your PHP code.
Try also flushing on the PHP side.
Code:
Adding linefeed:
socket_write($socket, "Hello\r\n");
String str = br.readLine(); expect a \n which is not sent by the PHP program.
Add this :
socket_write($socket, "Hello\n" ); // <<<=== '\n' added

Java TCP socket server with PHP client?

Hey there,
I am developing an TCP socket server in Java. The client(s) must connect to a webpage (in PHP)
Well, here come's my trouble.. They can connect to the specified host, but the server can't read the packets that the client send.
If I create the client in Java, it works 100%. Well, here are some snippets of my code. I hope someone have a answer for me. Because I'm stuck.
This is my little PHP script that sends:
<?php
set_time_limit(0);
$PORT = 1337; //the port on which we are connecting to the "remote" machine
$HOST = "localhost"; //the ip of the remote machine (in this case it's the same machine)
$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT) //Connecting to to server using that socket
or die("error: could not connect to host\n");
$text = "wouter123"; //the text we want to send to the server
socket_sendto($sock, $text, strlen($message), MSG_EOF, '127.0.0.1', '1337');
//socket_write($sock, $text . "\n", strlen($text) + 1) //Writing the text to the socket
// or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000, PHP_NORMAL_READ) //Reading the reply from socket
or die("error: failed to read from socket\n");
echo $reply;
?>
The socket side is:
package com.sandbox.communication;
public class PacketHandler {
public String processInput(String theInput) {
String theOutput = null;
if (theInput == "wouter123") {
theOutput = theInput;
}else {
theOutput = "Cannot find packet. The output packet is " + theInput;
}
return theOutput;
}
}
And this little code connects to the PacketHandler:
PacketHandler ph = new PacketHandler();
while ((inputLine = in.readLine()) != null)
{
outputLine = ph.processInput(inputLine);
out.println(outputLine);
}
As you are using readLine on your input stream so make sure your clients are sending the data with linefeed.
From the javadocs
readLine() Reads a line of text. A line is considered to be terminated
by any one of a line feed ('\n'), a carriage return ('\r'), or a
carriage return followed immediately by a linefeed.

how to read one string per time in java server socket from a php socket client

I am trying to read a string from php client socket in a java server socket. I am writing two strings in php socket client
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
socket_connect($this->socket, $this->host, $this->port)
$text = 'SGSA:PRINT:RECIBO';
socket_write($this->socket, $text, strlen($text));
$text = 'Mensagem para imprimir';
socket_write($this->socket, $text, strlen($text));
However when I read it in java like below
Socket clientSocket = server.accept();
InputStream in = clientSocket.getInputStream();
String msg;
try {
msg = IOUtils.toString( in );
} finally {
IOUtils.closeQuietly(in);
}
It reads two string together at once.
run-single:
SGSA:PRINT:RECIBOMensagem para imprimir
How can I read one string per time?

Categories

Resources