Send a tcp request from PHP Website to JAVA program - java

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)

Related

Socket messaging between Java Client and Python Server

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.

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.

Send data from PHP to Java tcp listener

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()

Can't read response from Java server in iOS client using NSInputStream

All,
This is my first time posting here -- I've searched for several hours over the past few days. This isn't the first client/server application I've made, and I'm completely stumped as to what's going wrong.
I've got a Java server (and it's able to correctly read a request from my iOS client -- it even generates a response and appears to send it correctly, though no data is available to read on the iOS client):
public void run() {
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStream out_stream = this.socket.getOutputStream();
StringBuilder request = new StringBuilder();
String request_buffer;
while ((request_buffer = in.readLine()) != null) {
request.append(request_buffer);
}
out_stream.write(processRequest(request.toString()).getBytes());
out_stream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
The supplied Java function is called as the result of spawning an instance of the class it's a member of, and it's initialized with the result of the accept() method of a ServerSocket. Everything seems to work fine here -- the following Python client is able to send a request (and even read a response):
DEFAULT_HOST = ''
DEFAULT_PORT = 2012
RECEIVE_BUFFER_SIZE = 4096
if __name__ == "__main__":
import sys, socket
port = DEFAULT_PORT
host = DEFAULT_HOST
if len(sys.argv) > 2:
host = sys.argv[1]
del sys.argv[1]
if len(sys.argv) == 2:
request = sys.argv[1]
print "Requesting: %s" % request
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(request)
s.shutdown(socket.SHUT_WR)
response = ""
message = True
while message:
message = s.recv(RECEIVE_BUFFER_SIZE)
response += message
print "Response: %s" % response
Before posting the iOS client, I've tested it with the following Python server (and the iOS client can read/write as expected.. this also works with the Python test client):
import os, sys
DEFAULT_HOST = ''
DEFAULT_PORT = 4150
# Simple test server
DEFAULT_SIZE = 4096
import socket
class Server:
def __init__(self, host, port, root, protocol, debug=True):
self.debug = debug
self.host = host
self.port = port
self.root = root
self.protocol = protocol
def __call__(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((self.host, self.port))
s.listen(5)
while True:
try:
c = s.accept()
print "Connection: %s" % str(c)
request = c[0].recv(DEFAULT_SIZE)
print "Request: %s" % request
try:
response = "test"
if self.debug:
print "Response: %s" % response
except Exception as ex:
print "Error generating response: %s" % ex
if response:
c[0].send(response)
else:
c[0].send("3rr0rZ")
c[0].close()
print
except Exception as ex:
print ex
if __name__ == "__main__":
host = DEFAULT_HOST
port = DEFAULT_PORT
args = sys.argv
# choose a port
if len(args) > 1 and args[1] == "-p":
if len(args) < 3:
raise Exception("Missing Argument for %s" % "-p")
port = int(args[2])
del args[1:3]
else:
port = DEFAULT_PORT
# check if root specified
if len(args) > 1:
root = os.path.realpath(args[1])
del args[1]
else:
root = os.getcwd()
print "Using:"
print "\tHost: %s" % host
print "\tPort: %s" % port
print "\tRoot: %s" % root
print
server = Server(host, port, root)
server()
Obviously this is a simplified server -- the problem isn't in how requests are generated. For a little more background, requests and responses are JSON strings, though that's not entirely relevant. As mentioned before, the Python client is able to successfully request and receive a response from both the Java and Python servers. The iOS client can successfully send requests to both the Python and Java servers, but it's only able to read a response from the Python server. Here's the relevant part of the iOS client:
- (NSData *)sendMessage:(NSData *)request
{
// Create low-level read/write stream objects
CFReadStreamRef readStream = nil;
CFWriteStreamRef writeStream = nil;
// Create high-level stream objects
NSInputStream *inputStream = nil;
NSOutputStream *outputStream = nil;
// Connect the read/write streams to a socket
CFStreamCreatePairWithSocketToHost(nil, (__bridge CFStringRef) self.address, self.port, &readStream, &writeStream);
// Create input/output streams for the raw read/write streams
if (readStream && writeStream) {
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
inputStream = (__bridge_transfer NSInputStream *)readStream;
[inputStream open];
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[outputStream open];
}
NSLog(#"Sending message to server: %#", request);
[outputStream write:[request bytes] maxLength:[request length]];
[outputStream close];
int size;
int buffer_size = 1024;
uint8_t buffer[buffer_size];
NSMutableData *response = [NSMutableData dataWithLength:0];
while (![inputStream hasBytesAvailable]);
NSLog(#"About to read");
while ([inputStream streamStatus] == NSStreamStatusOpen)
{
if ([inputStream hasBytesAvailable] && (size = [inputStream read:buffer maxLength:buffer_size]) > 0)
{
NSLog(#"Reading response data");
[response appendData:[NSData dataWithBytes:buffer length:size]];
}
}
NSLog(#"\tResponse:%#", response);
return response;
}
When reading from the Java server, the iOS client never gets past the line which reads:
while (![inputStream hasBytesAvailable]);
I've read all the documentation, forum posts, questions, etc. that I could find for a variety of search terms, but nothing has helped; I'm hoping someone here can shed some light on the issue! I've posted a slightly simplified/flattened version of the code I'm using, but, again, this should be sufficient for establishing context.. I'll happily post more code if it's necessary, and I appreciate any help or insight that you can share.
I'm purposefully not using a NSStreamDelegate, and I can't imagine that being an issue. If I were, I'd imagine that the problem would simply transform into the NSStreamEventHasBytesAvailable never happening.
Try my code, it works for me.
NSInputStream *inputStream;
NSOutputStream *outputStream;
-(void) init{
NSURL *website = [NSURL URLWithString:#"http://YOUR HOST"];
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL,CFBridgingRetain([website host]),9876, &readStream, &writeStream);
inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream open];
[inputStream open];
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
}
- (void) sendMessage {
// it is important to add "\n" to the end of the line
NSString *response = #"Say hello to Ukraine\n";
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];
int sent = [outputStream write:[data bytes] maxLength:[data length]];
NSLog(#"bytes sent: %d",sent);
do{
uint8_t buffer[1024];
int bytes = [inputStream read:buffer maxLength:sizeof(buffer)];
NSString *output = [[NSString alloc] initWithBytes:buffer length:bytes encoding:NSUTF8StringEncoding];
NSLog(#"%#",output);
} while ([inputStream hasBytesAvailable]);
}
public class ServerTest {
public static void main(String[] args) {
Thread thr = new Thread(new SocketThread());
thr.start();
}
}
class SocketThread implements Runnable {
#Override
public void run() {
try {
ServerSocket server = new ServerSocket(9876);
while (true) {
new SocketConnection(server.accept()).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class SocketConnection extends Thread {
InputStream input;
PrintWriter output;
Socket socket;
public SocketConnection(Socket socket) {
super("Thread 1");
this.socket = socket;
try {
input = socket.getInputStream();
output = new PrintWriter(new OutputStreamWriter(
socket.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
byte array[] = new byte[1024];
while (true) {
do {
int readed = input.read(array);
System.out.println("readed == " + readed + " "
+ new String(array).trim());
String sendString = new String(
"Hello Ukraine!".getBytes(),
Charset.forName("UTF-8"));
output.write(sendString);
output.flush();
} while (input.available() != 0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Your python server and Java server are not equivalent. In python you read like this:
request = c[0].recv(DEFAULT_SIZE)
which is reading upto 4096 bytes in a block. Whereas in Java you are using:
while ((request_buffer = in.readLine()) != null)
in.readLine() will block until it gets a end of line, OR until it gets the end of file. Likely this will get stuck until the client shuts down the socket. Are you sure the client is shutting down the output stream correctly? I'm not familiar with Objective C, but closing the output stream may not be the same is shutting down the write-side of the socket.
If you're in charge of both sides of the wire, I would have the client write a length header first (two bytes) followed by exactly that much data. Then the server can read two bytes, compute the length of the remaining data, and read exactly that much.
Length (2-bytes) | Data (length bytes)
----------------------------------------------------------
0x000C | Hello World!
By always sending length followed by data you can even send multiple messages without shutting down the socket very easily.

Communication between python client and java server

My aim is to send a message from python socket to java socket. I did look out on the resource mentioned above. However I am struggling to make the Python client talk to Java server. Mostly because (End of line) in python is different from that in java.
say i write from python client: message 1: abcd message 2: efgh message 3: q (to quit)
At java server: i receive message 1:abcdefghq followed by exception because the python client had closed the socket from its end.
Could anybody please suggest a solution for a consistent talk between java and python.
Reference I used: http://www.prasannatech.net/2008/07/socket-programming-tutorial.html
Update: I forgot to add, I am working on TCP.
My JAVA code goes like this:(server socket)
String fromclient;
ServerSocket Server = new ServerSocket (5000);
System.out.println ("TCPServer Waiting for client on port 5000");
while(true)
{
Socket connected = Server.accept();
System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
while ( true )
{
fromclient = inFromClient.readLine();
if ( fromclient.equals("q") || fromclient.equals("Q") )
{
connected.close();
break;
}
else
{
System.out.println( "RECIEVED:" + fromclient );
}
}
}
My PYTHON code : (Client Socket)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 5000))
while 1:
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
if (data <> 'Q' and data <> 'q'):
client_socket.send(data)
else:
client_socket.send(data)
client_socket.close()
break;
OUTPUT::
ON PYTHON CONSOLE(Client):
SEND( TYPE q or Q to Quit):abcd ( pressing ENTER)
SEND( TYPE q or Q to Quit):efgh ( pressing ENTER)
SEND( TYPE q or Q to Quit):q ( pressing ENTER)
ON JAVA CONSOLE(Server):
TCPServer Waiting for client on port 5000
THE CLIENT /127.0.0.1:1335 IS CONNECTED
RECIEVED:abcdefghq
Append \n to the end of data:
client_socket.send(data + '\n')
ya..you need to add '\n' at the end of the string in python client.....
here's an example...
PythonTCPCLient.py
`
#!/usr/bin/env python
import socket
HOST = "localhost"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.sendall("Hello\n")
data = sock.recv(1024)
print "1)", data
if ( data == "olleH\n" ):
sock.sendall("Bye\n")
data = sock.recv(1024)
print "2)", data
if (data == "eyB}\n"):
sock.close()
print "Socket closed"
`
Now Here's the java Code:
JavaServer.java
`
import java.io.*;
import java.net.*;
class JavaServer {
public static void main(String args[]) throws Exception {
String fromClient;
String toClient;
ServerSocket server = new ServerSocket(8080);
System.out.println("wait for connection on port 8080");
boolean run = true;
while(run) {
Socket client = server.accept();
System.out.println("got connection on port 8080");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
fromClient = in.readLine();
System.out.println("received: " + fromClient);
if(fromClient.equals("Hello")) {
toClient = "olleH";
System.out.println("send olleH");
out.println(toClient);
fromClient = in.readLine();
System.out.println("received: " + fromClient);
if(fromClient.equals("Bye")) {
toClient = "eyB";
System.out.println("send eyB");
out.println(toClient);
client.close();
run = false;
System.out.println("socket closed");
}
}
}
System.exit(0);
}
}
`
Reference:Python TCP Client & Java TCP Server
here is a working code for the same:
Jserver.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Jserver{
public static void main(String args[]) throws IOException{
ServerSocket s=new ServerSocket(5000);
try{
Socket ss=s.accept();
PrintWriter pw = new PrintWriter(ss.getOutputStream(),true);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br1 = new BufferedReader(new InputStreamReader(ss.getInputStream()));
//String str[20];
//String msg[20];
System.out.println("Client connected..");
while(true)
{
System.out.println("Enter command:");
pw.println(br.readLine());
//System.out.println(br1.readLine());
}
}
finally{}
}
}
Client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 5000 # Reserve a port for your service.
s.connect((host, port))
while 1:
print s.recv(5000)
s.send("message processed.."+'\n')
s.close
I know it is late but specifically for your case I would recommend RabbitMQ RPC calls. They have a lot of examples on their web in Python, Java and other languages:
https://www.rabbitmq.com/tutorials/tutorial-six-java.html
for the people who are struggling with,
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
your can also use
.encode() to send the data

Categories

Resources