Java Socket Server hangs while reading data - java

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

Related

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");

java client side socket, if refused

This client side is talking to a single threaded server. Now, what i'm trying to do is, if client#2 tries to connect to the socket while client#1 is already actively connected to the server side, to do something else. so for example,
if(socket1.gotrefused){
system.out.println("It got refused");
My code below, (It's working perfectly for me, i just want to add the above one way or another..)
Socket socket1;
int portNumber = 4445;
socket1 = new Socket(InetAddress.getLocalHost(), portNumber);
BufferedReader br = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
PrintWriter pw = new PrintWriter(socket1.getOutputStream(), true);
pw.println("Hello");
pw.println("Hello");
pw.println("Hello");
pw.println("Hello");
String input = br.readLine();
while ((input = br.readLine()) != null) {
if(input.equals("Hi")){
pw.println("Hello");
}
else if(input.equals("Done")){
break;
}
br.close();
pw.close();
socket1.close();
}

Basic Java Echo Socket Communication Error

I have been looking through the multitudes of explanation of basic Java Socket use, and have constructed the following basic code for my own Server/Client echo pair. However, there is some hangup in the client code that I cannot find for the life of me. Perhaps someone else can spot it?
// Server Code:
try (ServerSocket serverSocket = new ServerSocket(22222);
Socket cSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(cSocket.getOutputStream());
BufferedReader in = new BufferedReader(
new InputStreamReader(cSocket.getInputStream()))) {
System.out.println("Client connected: " + cSocket.getInetAddress().getHostAddress());
// console DOES print ^this line and correct IP when client is run.
String inLine;
while (true) {
inLine = in.readLine();
out.println(inLine);
if (inLine.equals("exit")) break;
}
// client code
try (Socket socket = new Socket("localhost", 22222);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));) {
String userIn;
while (true) {
System.out.print("Client> ");
userIn = consoleIn.readLine();
out.println(userIn); // code hangs here.
out.flush();
System.out.println("Server> " + in.readLine());
if (userIn.equals("exit")) break;
}
It isn't blocking there. It's blocking in the readLine() from the server. Try a flush() after the println() in the server.

Java readLine and PHP write interaction

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

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