Up to date comunnication java to python - java

I'm trying to run python script from java and when something would change in java I want to send information about it to python program. I don't know the best solution for it. I can run python script and send start information to it but then problems start. I think about sending data through tcp/ip connection, but when I try to do that I have error in python script:
Caused by: Traceback (most recent call last):
File "pythonScript.py", line 2, in <module>
import socket
ImportError: No module named socket
at org.python.core.Py.ImportError(Py.java:264)
at org.python.core.imp.import_first(imp.java:657)
at org.python.core.imp.import_name(imp.java:741)
at org.python.core.imp.importName(imp.java:791)
at org.python.core.ImportFunction.__call__(__builtin__.java:1236)
at org.python.core.PyObject.__call__(PyObject.java:367)
at org.python.core.__builtin__.__import__(__builtin__.java:1207)
at org.python.core.__builtin__.__import__(__builtin__.java:1190)
at org.python.core.imp.importOne(imp.java:802)
at org.python.pycode._pyx0.f$0(pythonScript.py:27)
at org.python.pycode._pyx0.call_function(pythonScript.py)
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyCode.call(PyCode.java:18)
at org.python.core.Py.runCode(Py.java:1197)
at org.python.core.__builtin__.execfile_flags(__builtin__.java:538)
at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:156)
at sample.PythonClass.runPythonScript(PythonClass.java:26)
at sample.Controller.handleSubmitButtonActionIp(Controller.java:30)
... 58 more
So it's some problem with scoket import, but when I run this program normaly there is no error. It's code of function which I use to run python script:
public void runPythonScript(boolean isCameraOn, String ip){
System.out.println(ip);
String[] arguments = {ip};
PythonInterpreter.initialize(System.getProperties(),System.getProperties(), arguments);
PythonInterpreter python = new PythonInterpreter();
StringWriter out = new StringWriter();
python.setOut(out);
python.execfile("pythonScript.py");
String outputStr = out.toString();
System.out.println(outputStr);
}
And it's code of python client:
import sys
import socket //ERROR
print("poczatek")
print(sys.argv[0])
print("koniec")
HOST = "localhost"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(0)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
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")
Java server:
public void sendDataToPythonScript(boolean isCameraOn, String ip) throws
IOException {
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);
}

Try importing the embedded socket module
import _socket
If that does not fix it try setting the path for python modules this link should explain how to set the path for python in java.

Related

I want to make connection between raspberrypi as server and java desktop app as client via socket

I want to make connection between raspberry pi and java desktop app using socket the message doesn't send to java it comes NULL and in rpi python, it comes with an exception .what should i do?
server in raspberry pi
import socket
import time
try:
host=''
port=9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(5)
print("socket is listening..")
while True:
con,add=s.accept()
print ("connect to ",add)
messag = con.recv(1024)
messag = messag.decode('utf-8')
print ("messag from client ",messag)
print ("done recive..")
time.sleep(2)
if not msgrecv:
break
#send to java
sendMsg = "connection..."
sendMsg =sendMsg.encode()
con.sendall(sendMsg)
print ("Done send ")
con.close()
s.close()
except Exception as e:
print(e)
client in java
try {
Socket soc = new Socket("192.168.1.4", 9999);
DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
DataInputStream in =new DataInputStream(soc.getInputStream());
/////////////////////////////////
while (soc.isConnected()) {
////////////////send
dout.writeUTF("welecome...connect"); //wite string
dout.flush();
//////recive (String)
String msg = in.readUTF();
System.out.println("Server: " + msg);
///////////////
dout.flush();
dout.close();
soc.close();
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
the output
Socket is Listening....
('connect to ', ('...',... ))
messag from Client', u'\x00\x12welecome...connect')
done received! !!
connection Closed...
note : this is exception in python
exception [Errno 9] Bad file descriptor
the message didn't come it come NULL
4.Error in java
run:
null
BUILD SUCCESSFUL (total time: 3 seconds)

Connecting a Java Server with a Python Client

So here's the thing, I have a basic java server that sends back to the client what ever it receives from it. The client is written in python. I'm able to make the first connection as in the server sends the client a message confirming the connection. But when I want the client to send the server something is does nothing. I'm not sure if the problem with the client not sending or the server not receiving.
Here's the code for the server:
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter outs =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
outputLine = "Hello socket, I'm server";
outs.println(outputLine);
outs.println("I' connected");
while ((inputLine = in.readLine()) != null) {
outputLine = inputLine;
outs.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} 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 here's the client :
import socket
HOST = "localhost"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print (socket.getaddrinfo(HOST,PORT))
buffer_size = 100
while True :
data = sock.recv(buffer_size)
print ('you recieved :' , data)
test = input('send here\n')
sock.sendall(bytes(test, 'utf-8'))
print ('you sent : ' , test)
In the Python client:
Your prompt contains a \n but the result from input does not? Try adding a \n to test before sending.

PHP socket Connection refused (Java server)

I have a working Java socket, but I need some help connecting to it with PHP.
My problem: I can connect to the Java socket from a Java client and send/receive messages, but when I try to connect to the same socket with PHP, it won't connect.
This is what I have for the socket in the while loop: (keep in mind this part works)
Socket socket = serverSocket.accept();
System.out.println("Got connection");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String cmd = in.readLine();
System.out.println("Received: " + cmd);
String response = "It worked. Received: " + cmd;
out.println(response);
...
And just to show the other half that works, this is the client:
Socket socket = new Socket("<ip>", port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("test msg");
out.flush();
System.out.println("Sent message");
String r = in.readLine();
System.out.println("Response: " + r);
Now for the part that doesn't work.
This is what I am doing to try and connect with PHP:
$s = fsockopen('<ip>', $port, $errno, $errstr, 25);
if (!$s) {
echo 'Error: '.$errstr;
die;
}
Running that outputs: "Error: Connection refused"
Does anyone know how I can diagnose why the PHP can't connect but the Java client can? They are both accessing the socket externally, and since the Java client can connect it's not blocked. Is there some protocol I forgot to set?
I've looked at dozens of other people with the same question but nobody has provided an answer.
Did you look in the php.ini if fsockopen is allowed ?
1、php.ini, look for line: disable_functions = fsockopen
2、php.ini, see allow_url_fopen = On or allow_url_fopen = Off

Socket Server will not receive properly

I am trying to make a socket server, I am connecting through putty to this server. Whenever I type "hi" it says "no" rather than "hi" which I want it to do. I found this on A java website. If you could tell me what I am doing wrong that would be great. Thanks!
int port = 12345;
ServerSocket sock = new ServerSocket(port);
System.out.println("Server now active on port: " + port);
Socket link = sock.accept();
System.out.println("Interface accepted request, IP: " + link.getInetAddress());
BufferedReader input = new BufferedReader(new InputStreamReader(link.getInputStream()));
PrintWriter output = new PrintWriter(link.getOutputStream(), true);
output.println("ISEEYOU");
String inputLine;
Thread.sleep(1500);
while((inputLine = input.readLine()) != null) {
if(inputLine.equals("hi")) {
output.println("hi");
}else{
output.println("no");
}
}
Your Java program is correct.
I've tried your code, just added System.out.printf("[%s]", inputLine); as first line in the while loop to ensure, what I get from putty.
I guess your problem is the protocol putty uses to connect. It worked with RAW for me. See below the session setting I've used:
EDIT:
According to your comment I added some code for a simple client, that reads the line from console, sends it to the server and prints the echo back to console.
public void Client() throws IOException {
// Client that closes the communication when the user types "quit"
Socket socket = new Socket("localhost", 8080);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
BufferedReader user = new BufferedReader(new InputStreamReader(System.in));
String line;
while(!(line = user.readLine()).equals("quit")) {
ps.println(line); // Write to server
System.out.println(reader.readLine()); // Receive echo
}
socket.shutdownOutput(); // Send EOF to server
socket.close();
}
The corresponding server would look like this:
public void server() throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
// Just read a line and echo it till EOF
String line;
while((line = reader.readLine()) != null) ps.println(line);
}
You might need to change the port I used here, if 8080 is already binded on your machine. Also you might want to have the server running on another computer then the client. In this case you need to change "localhost".

PHP/Java Sockets - Strange error?

Java code:
package servermonitor;
import java.io.*;
import java.net.*;
public class CommandListener extends Thread
{
public int count = 0;
public void run()
{
try
{
ServerSocket server = new ServerSocket(4444);
while(true)
{
System.out.println("listening");
Socket client = server.accept();
System.out.println("accepted");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("got reader");
String data = "";
String line;
while((line = in.readLine()) != null)
{
System.out.println("inloop");
data = data + line;
}
System.out.println("RECIEVED DATA: " + data);
in.close();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
count++;
out.write("gotcha: " + count + "\\n");
out.flush();
}
}
catch(IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
Java console (when I access the following PHP script):
listening
accepted
got reader
PHP code:
<?php
$PORT = 4444; //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 = "Hello, Java!\n"; //the text we want to send to the server
socket_write($sock, $text, strlen($text) + 1) //Writing the text to the socket
or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000) //Reading the reply from socket
or die("error: failed to read from socket\n");
echo $reply;
?>
When I navigate to the PHP page, it loads forever.
Any ideas?
The Java side expects a newline in its input. You're not sending one, so readLine never finishes.
Also, readLine won't return null until the socket is closed or an exception occurs (I/O error for instance). You need to return some data as soon as you've read a line if your protocol works like that.
As it was told, you need to close socket to readLine returns null.

Categories