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.
Related
I try to create a Socket messager between a Java Client and Python Server. It works to send a message ("Testdata") from client to server and print it out. But after input and send a message from server to client, I get no output from client. The client 'freezes' and must be terminated.
What is the problem with my client input?
Terminal Server:
py socketServer.py
Connection from: ('127.0.0.1', 57069)
from connected user: Testdata
> Test
send data..
Terminal Client:
java socketClient
Testdata
Python-Server:
import socket
def socket_server():
host = "127.0.0.1"
port = 35100
server_socket = socket.socket()
server_socket.bind((host, port))
server_socket.listen(2)
conn, address = server_socket.accept()
print("Connection from: " + str(address))
while True:
data = conn.recv(1024).decode()
if not data:
break
print("from connected user: " + str(data))
data = input('> ')
conn.send(data.encode())
print("send data...")
conn.close()
if __name__ == '__main__':
socket_server()
Java-Client:
private static void socketTest(){
String hostname = "127.0.0.1";
int port = 35100;
try (Socket socket = new Socket(hostname, port)) {
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, false);
BufferedReader input =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
Scanner in = new Scanner(System.in);
String text;
do {
text = in.nextLine();
writer.print(text);
writer.flush();
System.out.println("from server: " + input.readLine());
} while (!text.equals("exit"));
writer.close();
input.close();
socket.close();
}
}
This is because python messages are not explicitly finished with \r\n like #carlos palmas says in this answer.
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
I need to write a program using Java to connect a socket, send authenticate data and receive the answer. I have a code in Python that works and I'm using this as an example.
I'm able to connect but after send data I didn't receive anything.
Below the java code that I wrote:
String hostname = "remoteHost";
int port = 4200;
Socket socket = new Socket(hostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
JSONObject json = new JSONObject();
JSONObject params = new JSONObject();
params.put("code", "authCode");
json.put("jsonrpc", "2.0");
json.put("method", "authenticate");
json.put("params", params);
json.put("id", "0");
out.write(json.toString());
System.out.println(in.readLine());
Below the example in Python:
import socket, json
from dateutil import parser
host = "app.sensemetrics.com"
port = 4200
apiCode = "YourAPIKey"
# Open a new socket connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
# Send the authentication request
handshake = json.dumps({
"jsonrpc": "2.0",
"method": "authenticate",
"params": {
"code" : apiCode
},
"id": 0
})
s.send(handshake)
# Parse the response
jsonFrame = decodeOneJsonFrame(s)
response = json.loads(jsonFrame)
print("\r\nHandshake Exchange:\r\n" + " --> " + handshake + "\r\n" + " <-- " + jsonFrame)
# Close the socket connection
s.close()
out.write(json.toString());
I think you should also call out.flush().
Don't forget to call flush on other side too, after writing response so you can read it with System.out.println(in.readLine());
See here
Use try-with-resources to automatically close open resources and OutputStream.flush - to flush the data to the stream.
Modify your code as below:
String hostname = "remoteHost";
int port = 4200;
JSONObject json = new JSONObject();
JSONObject params = new JSONObject();
params.put("code", "authCode");
json.put("jsonrpc", "2.0");
json.put("method", "authenticate");
json.put("params", params);
json.put("id", "0");
try (
Socket socket = new Socket(hostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
out.write(json.toString());
out.flush();
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
I want to send a TCP Request from my website to my java application. So my java application should be able to receive a JSON array and print it.
I searched around for a few hours, but I could not find a solution.
Here is, what I have in PHP:
<?php
$array = array(
0 => "test",
1 => "test1"
);
json_encode($array);
$host = "tcp://localhost";
$port = 8123;
$data = json_encode($array);
$errstr = '';
$errno = '';
if ( ($fp = fsockopen($host, $port, $errno, $errstr, 3) ) === FALSE)
echo "$errstr ($errno)";
else {
print 'SUCCESS!<br />';
fwrite($fp, $data);
while (! feof($fp)) {
echo fgets($fp, 4096);
}
fclose($fp);
}
My Java code:
public class tcp {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(8123);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
connectionSocket.close();
}
}
}
So as you should see, I never have done something like this before.
My questions:
1) Do I have to open port "8123", also when the website and my application will run on localhost (ubuntu / debian)? -> how should I open them correctly?
2) When I start my app, I think I have to create the "tcp" java object. -> tcp tcp = new tcp - is this enough or do I have to call a method other something similar?
3) What do I have to change in my code? The Application does just nothing when I send a request...
So I hope you guys can help me with my problem :)
Greets
EDIT:
When I try to run my PHP script, I git following error:
Warning: fsockopen(): unable to connect to tcp://localhost:8123 (Connection refused) in /PATH_TO_PHP/TCPSEND/index.php on line 16
Connection refused (111)
So, I have a very basic test set up to see if i can send data from a php web page to a java app running on the same server.
The java app is dead simple, it just listens on a TCP socket for data
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
connectionSocket.close(); //this line was part of the solution
}
}
}
I have tried two ways to send and read the response with php, but none seem to work. I get a connection OK and data sent OK, but the server doesn't print anything nor respond with anything so I dont know why it's saying it's OK :)
Method 1
$host = "tcp://localhost";
$port = 6789;
$data = 'test' . PHP_EOL; //Adding PHP_EOL was the other part of the solution
$errstr = '';
$errno = '';
if ( ($fp = fsockopen($host, $port, $errno, $errstr, 3) ) === FALSE)
echo "$errstr ($errno)";
else {
print 'SUCCESS!<br />';
fwrite($fp, $data);
while (! feof($fp)) {
echo fgets($fp, 4096);
}
fclose($fp);
}
Method 2
$host = "localhost";
$port = 6789;
$data = 'test';
if ( ($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === FALSE )
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error());
else
{
echo "Attempting to connect to '$host' on port '$port'...<br>";
if ( ($result = socket_connect($socket, $host, $port)) === FALSE )
echo "socket_connect() failed. Reason: ($result) " . socket_strerror(socket_last_error($socket));
else {
echo "Sending data...<br>";
socket_write($socket, $data, strlen($data));
echo "OK<br>";
echo "Reading response:<br>";
while ($out = socket_read($socket, 2048)) {
echo $out;
}
}
socket_close($socket);
}
EDIT
Apparently fsockopen() has a problem connecting to localhost from a comment I found at PHP fsockopen doesnt return anything so changed to 127.0.0.1 but still not working.
Try changing $data = 'test' to $data = "test\n" and see if that helps.
Close the socket on the server when your done otherwise the client will block in the while loop waiting for more data:
outToClient.writeBytes(capitalizedSentence);
connectionSocket.close()