Java readLine and PHP write interaction - java

I have a strange trouble with TCP server (Java) and client (PHP). Java server hangs at a readLine..
Please see code above.
Java server:
while (true) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
String inputLine;
if ((inputLine = in.readLine()) != null) {
System.out.println("Server: " + inputLine);
out.println(handleCommand(inputLine));
} else {
System.out.println("Ooops...");
}
}
PHP client:
$fp = fsockopen("127.0.0.1", 6789, $errno, $errstr, 30);
$result = '';
if (!$fp) {
ErrorLog(ALERT, "-", "Unable to connect to java server! $errstr ($errno)");
$result = 'ERROR|Unable to connect to RmServer';
} else {
fwrite($fp, $command.PHP_EOL);
while (!feof($fp)) {
$result .= fgets($fp, 128);
}
fclose($fp);
}
I also tried on a client side:
fwrite($fp, $command."\n");
fwrite($fp, $command."\r\n");
But result is the same.
But when I use Java client it works fine! May be it is some encoding related problem? I think some magic happens when I type ENTER after command in console.
Java client(works) code:
if ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print("input: ");
} else {
System.out.print("Opppppps..");
}
ADD:
If I send empty string by Java client after sending by PHP client I see the following output:
Server: test\ntest\n

Related

Java Socket Server hangs while reading data

I have a PHP file talking to a Java socket server, and when I send data over, my java server gets stuck (hung, frozen) on inputLine = in.readLine(). I've debugged and found that it's only when I read data, this happens.
Here's my java method for the server:
public void start_echo_server(int port){
main.getProxy().getConsole().sendMessage(new TextComponent(ChatColor.GOLD + "STARTING SOCKET LISTENER (echo)"));
int portNumber = port;
try {
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
// accepted the connection
main.getProxy().getConsole().sendMessage(new TextComponent(ChatColor.GOLD + "ACCEPTED"));
// in stream
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// outstream
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
String final_line = sb.toString();
main.getProxy().getConsole().sendMessage(new TextComponent(ChatColor.GOLD + "IN: " + final_line));
//String final_ret = parser.parse_message(final_line);
//main.getProxy().getConsole().sendMessage(new TextComponent(ChatColor.GOLD + "FINAL: " + final_ret));
out.println(final_line);
in.close();
out.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And here's my PHP file:
<?php
if( isset($_POST['username']) )
{
$username = $_POST['username'];
parse($username);
}else{
echo "Missing parameters!";
exit();
}
function parse($username){
//Must be same with server
$host = "127.0.0.1";
$port = 59090;
// No Timeout
//Create Socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
//Connect to the server
$result = socket_connect($sock, $host, $port) or die("Could not connect toserver\n");
$message = "player_online ". $username;
//Write to server socket
$len = strlen($message);
socket_write($sock, $message, $len) or die("SENDING ERROR ". $message ." \n");
//Read server respond message
$result = socket_read($sock, 1024) or die("RESPONSE ERROR ". $message ." \n");
echo "Reply From Server :".$result;
//Close the socket
socket_close($sock);
}
?>
The problem is when I do socket_write (writing the data) on the PHP side, but the issue is at the java line while ((inputLine = in.readLine()) != null) {.
Thanks so much!
Solved!
I was reading multiple lines with only one line coming in, while I didn't include a newline (\n) after the message (which signifies that the previous message was a line that is finished).
Replace PHP $message = "player_online ". $username; with $message = "player_online ". $username ."\n";
Also had to replace Java
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
String final_line = sb.toString();
with
String inputLine = in.readLine();
String final_line = inputLine;
Try changing the while condition to something you control as a proof of concept i.e read during 1 minute or so, if that unstucks ypu then do nor read while in.readline but fimd something else, it happened to me on some ssh connection, we then set the while condition to read while channel is open...will try to find that code and add it here if you dont get to somerhing based on the above proof of concept

The DataOutputStream text from Server to Client is indented weird and produces a 4

Right now, I'm trying to make a server that can display messages to the client when they connect (through localhost). When I connect through telnet, it gives me weird indentation. The code for the server is:
private ServerSocket middleman;
private int port = 8080;
private Socket client;
protected void createSocketServer()
{
try
{
while (true){
middleman = new ServerSocket(port);
client = middleman.accept();
middleman.close();
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String line;
//Client stuff
DataOutputStream dOut = new DataOutputStream(client.getOutputStream());
while((line = in.readLine()) != null)
{
System.out.println("echo: " + line);
dOut.writeByte(1);
dOut.writeUTF("Good day to you user. Here is a selection of poems " + "\n");
dOut.writeUTF("1. Cupcake Poem" + "\n");
dOut.flush();
//Response
if(line.equals("cupcake")){
try{
FileReader fileReader = new FileReader(poem);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String poemLine;
while((poemLine = bufferedReader.readLine()) != null){
stringBuffer.append(poemLine);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
//System.out.println(stringBuffer.toString());
dOut.writeUTF(stringBuffer.toString());
dOut.flush();
} catch(IOException e){
e.printStackTrace();
}
}
else{
System.out.println("wrong!, the line is:" + line);
}
}
}
}
catch(IOException e)
{
System.out.println(e);
}
}
On the client side, I'll open the command prompt and type telnet localhost 8080 then I'll type something like "fish". It will print
[?]Good day to you user. here is a selection of poems
1. Cupcake Poem
Why does it do this? If I type "cupcake" on client, it will read the file, but have weird spacing. Is this something to do with Telnet?
For telnet the correct end-of-line sequence is "\r\n". Newline by itself will only go down to the next line, but it will not back up to the first column, which what the carriage-return does.
Also note that the order matters, the telnet specifications says that it has to be "\r\n", in that order.
Also, you don't have to append the output with the newline-sequence like you do. You can write it all as a single string:
dOut.writeUTF("1. Cupcake Poem\r\n");

Domain fronting proxy in Java, won't get "pull method" proxy to work

I'm currently working on a project that uses a technique called "domain fronting". In short: it send internet traffic to a CDN (in this case Google) over an encrypted connection, and the CDN then passes back this info to the proxy. This way you can circumvent censorship (as long a the CDN isn't blocked), because the real destination is unknown to a observer. (To read more about domain fronting, here is the original paper) A number of applications like Signal and Tor already use this technique, but there isn't a general use proxy that just proxies a tcp socket through Google to the other end. I decided to go work on that and it's almost finished: the HTTP encoding part and the code at Google's servers is working. The only problem is the real proxying part.
This is the structure of the proxy:
source-->client proxy-->[Google]-->server proxy-->destination
The difference with a general proxy is that HTTP is a request based protocol and thus can't do the asynchronous things normal proxies do. My setup is to make a request from the client once in 100ms to the server sending the bytes the client received to the server. The server reads the bytes from the destination and sends them back to the client. Than the server and client both write their received bytes to the original sockets and another roundtrip starts in 100ms.
Here is my code to this point (I only pasted the relevant part, this code is not domain fronting yet):
Client:
try {
ServerSocket serverSocket = new ServerSocket(8082);
System.out.println("client proxy is listening for connections");
Socket source = serverSocket.accept();
BufferedReader sourceIn = new BufferedReader(new InputStreamReader(source.getInputStream()));
PrintWriter sourceOut = new PrintWriter(source.getOutputStream(), false);
while(true) {
Socket server = new Socket("localhost", 8081);
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter out = new PrintWriter(server.getOutputStream(), false);
//read what the source has for the server
System.out.println("start reading source socket");
System.out.println("available: " + source.getInputStream().available());
char[] buffer = new char[15000];
int bytesRead = 0;
if(source.getInputStream().available() != 0) {
bytesRead = sourceIn.read(buffer);
byte[] bytesToSend = new byte[bytesRead];
bytesToSend = Arrays.copyOfRange(new String(buffer).getBytes(), 0, bytesRead);
out.print((byte) 1);
out.print(bytesToSend);
out.flush();
System.out.println("Sent to server: " + new String(bytesToSend) + " bytesRead: " + bytesRead);
} else {
out.print((byte) 0);
out.flush();
System.out.println("Sent to server: nothing");
}
//read what the server has for the source
buffer = new char[15000];
bytesRead = 0;
while((bytesRead = in.read(buffer)) == -1) {
System.out.println("didn't receive any bytes from server");
Thread.sleep(20);
}
byte[] bytesToSend = Arrays.copyOfRange(new String(buffer).getBytes(), 0, bytesRead);
if(bytesToSend[0] == '1') {
sourceOut.print(bytesToSend);
sourceOut.flush();
System.out.println("Sent to source: " + new String(bytesToSend));
} else {
System.out.println("Server has nothing for source; bytesToSend: " + new String(bytesToSend));
}
in.close();
out.close();
server.close();
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
Server:
try {
Socket destination = new Socket("192.168.0.150", 22);
BufferedReader destinationIn = new BufferedReader(new InputStreamReader(destination.getInputStream()));
PrintWriter destinationOut = new PrintWriter(destination.getOutputStream(), false);
ServerSocket server = new ServerSocket(8081);
while(true) {
Socket clientSocket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), false);
System.out.println("received new connection from client");
//read what client has for destination
char[] buffer = new char[15000];
int bytesRead = 0;
while((bytesRead = in.read(buffer)) == -1) {
System.out.println("didn't receive any bytes from client");
Thread.sleep(20);
}
byte[] bytesToSend = Arrays.copyOfRange(new String(buffer).getBytes(), 0, bytesRead);
if(bytesToSend[0] == (byte) 1) {
destinationOut.print(bytesToSend);
destinationOut.flush();
System.out.println("Sent to destination: " + new String(bytesToSend));
} else {
System.out.println("Client has nothing for destination");
}
//read what distination has for client
System.out.println("start reading destination socket");
System.out.println("available: " + destination.getInputStream().available());
buffer = new char[15000];
if(destination.getInputStream().available() != 0) {
bytesRead = destinationIn.read(buffer);
bytesToSend = new byte[bytesRead];
bytesToSend = Arrays.copyOfRange(new String(buffer).getBytes(), 0, bytesRead);
out.print("1");
out.print(new String(bytesToSend));
out.flush();
System.out.println("Sent to client: " + new String(bytesToSend) + " bytesRead: " + bytesRead);
} else {
out.print((byte) 0);
out.flush();
System.out.println("Sent to client: nothing");
}
out.close();
in.close();
clientSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
When I run this code to connect to a SSH server, the SSH client freezes and it seems like the proxy server doesn't respond to the proxy client anymore.
I really hope someone can help me with this, if you need extra info, just let me know! :)

Prevent server terminating in client (golang) server (Java) application

I have a simple echo-server in Java:
int portNumber = 4444;
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
System.out.println(inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
and a simple golang client:
func main() {
fmt.Println("start client")
conn, err := net.Dial("tcp", "localhost:4444")
if err != nil {
log.Fatal("Connection error", err)
}
conn.Write([]byte("hello world"))
conn.Close()
fmt.Println("done")
}
When I start the server and then run the client, the server echo's "hello world" as expected but then the server exits/terminates.
Q. How do I prevent this Java termination and force the server to continually wait for more client requests?
When the client terminates, the readLine on server side will result in the end of the stream. So if you want the server to continuously listen for new connections the simply put the above server code in a endless loop.
e.g.
while (true) {
// above code
}
For a play application that would be adequate.

socket server not sending data to php client

I am trying to create a communication between a socket server in java and a php client however apparently no data is sent from server to client. I have tried plenty of methods for writing data to socket but none of those did work although i am able to send data from client to server.
Server side code
int port = 5566, maxConnections = 0;
int nrCon=0;
ServerSocket listener = new ServerSocket(port);
Socket server;
while((nrCon++<maxConnections)|| (maxConnections ==0)){
server = listener.accept();
BufferedReader in = new BufferedReader (new InputStreamReader(server.getInputStream()));
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( server.getOutputStream() ) );
//PrintWriter out = new PrintWriter(server.getOutputStream(), true);
//ObjectOutputStream oos = new ObjectOutputStream(server.getOutputStream());
//DataOutputStream os = new DataOutputStream(server.getOutputStream());
String line, data="";
while((line = in.readLine())!= null ){
System.out.println("wowowoowow");
data = data + line;
String[] coords = data.split(" ");
}
out.print("ROUTE DIJKSTRA: \n");
//out.flush();
//os.writeUTF("testetstets");
client side code
$PORT = 5566;
$HOST = "localhost";
$sock = socket_create(AF_INET, SOCK_STREAM, 0)
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT)
or die("error: could not connect to host\n");
socket_set_nonblock($sock);
if ( $_POST['v_lat']=="undefined" && $_POST['v_lng']=="undefined" ){
$text = "$sLng $sLat $dLng $dLat";
}else{
$vLat = $_POST['v_lat'];
$vLng = $_POST['v_lng'];
$text = "$sLng $sLat $vLng $vLat $dLng $dLat";
}
$sent = socket_write($sock, $text, strlen($text)+1);
$sock_err = socket_last_error($sock);
if ($sent === false) {
echo "could not send data to server\n";
break;
}else {
echo "sent ".$sent." bytes\n";
}
echo "sock error send: ".$sock_err." \n";
$result = socket_read ($sock, 2048);
$sock_err = socket_last_error($sock);
echo "sock err: ".$sock_err." \n";
echo "Reply From Server :".$result;
What i do get from sock_err call is the error code 10035 which is apparently for server not sending the data no matter how many socket writing data methods i tried.
I ran out of ideas.

Categories

Resources