On the python server i plan to receive parameters from a java client, run them through a neural network and send the result back. The messages will be numpy arrays converted to strings for the communication process.
However i'am not that far yet trying to pass some dummy string from the client just to envoke the server routine and everything is fine when i just send a string back. However when i call mod.predict(arr) INSIDE the loop or do not concatenate the received data to the reply, the server doesn't react. Does anyone have an idea how i could get this done?
Server - Python:
HOST = 'localhost'
PORT = 7777
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
while True:
conn, addr = s.accept()
data = conn.recv(1024)+"\r\n"
pred = mod.predict(arr)
reply = 'Answer..' + pred + data # +'\r\n'
if not data:
break
conn.send(reply)
conn.close()
Client - Java:
Socket socket = new Socket("localhost", 7777);
OutputStream out = socket.getOutputStream();
PrintStream ps = new PrintStream(out, true);
ps.println("Hello Python!");
InputStream in = socket.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(in));
while (buff.ready()) {
System.out.println(buff.readLine());
}
socket.close();
Server code:
import socket
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sock.bind(("localhost", 5000))
sock.listen()
while True:
try:
sock.listen()
conn, addr = sock.accept()
print(conn.recv(1024))
conn.send(b"Hello world from Python")
conn.close()
except:
break
sock.close()
This is correct, because cURL says so.
➜ ~ curl -v localhost:5000
* Rebuilt URL to: localhost:5000/
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> GET / HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
>
* Connection #0 to host localhost left intact
Hello world from Python%
Oh, and your client code is wrong as well. You need to create a streaming socket, not a datagram socket (which is what you have).
Client code:
import java.net.*;
import java.io.*;
class Main
{
public static void main(String args[]) throws Exception
{
// This constructor creates a streaming socket
Socket socket = new Socket(InetAddress.getByName(null), 5000);
OutputStream out = socket.getOutputStream();
PrintStream ps = new PrintStream(out, true);
ps.println("Hello Python!");
InputStream in = socket.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(in));
while (buff.ready()) {
System.out.println(buff.readLine());
}
socket.close();
}
}
This is what the server code looks like now. All expressions are calculated and printed correctly in the console when i start the server from commandline and then run the java-client from eclipse. What really is strange is that when i pass some string as reply and it seem to work, it can stop working when i just add some print argument in the while loop like in the code below.
import socket
import sys
import pickle
import numpy as np
f=open('C:\\nn.pkl','rb')
mod=pickle.load(f)
HOST = 'localhost'
PORT = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.bind((HOST, PORT))
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
while True:
try:
s.listen(10)
conn, addr = s.accept()
data = conn.recv(1024)
print data
arr = np.array([1.0, 0.9712, 0.01019, 0.333, 0.01008, 0.5625, 0.75, 0.4, 0.25, 0.6, 0.0])
pred = np.array_str(mod.predict(arr))
print pred
reply = "Answer.." + pred
conn.send(reply)
conn.close()
except:
break
s.close()
Additionaly when i repeatedly run the java client while the server is running, i somtimes get an answer and somtimes not because buff.ready() isn't true on every run.
public static void main(String args[]) throws IOException {
Socket socket = new Socket(InetAddress.getByName(null), 5000);
OutputStream out = socket.getOutputStream();
PrintStream ps = new PrintStream(out, true);
ps.println("Hello Python!");
InputStream in = socket.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(in));
while (buff.ready()) {
System.out.println(buff.readLine());
}
}
Related
What is port I can use for someone can connect me and get message connection is established ?
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"),true);
printWriter.println("Connection is established");
Thank you
Welcome to SO Deny
The port is for you (the server) to decide.
The client needs to know what port to connect to, so it can get a response.
For your question, just don't pick some port that currently your computer is using will be fine. Such as like 20 or 80, those ports are using in real http data transferring
In the below codes, your can notice that I just randomly pick a port, to note that, both ports in sender and receiver have to be the same, otherwise, you will not get the message.
This one is TCPSender.py
from socket import *
serverName = 'localhost'
serverPort = 8797
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input('Input lowercase sentence:')
clientSocket.send(sentence)
modifiedSentence = clientSocket.recv(1024)
print ('From Server:', modifiedSentence)
clientSocket.close()
This one is TCP Receiver.py
from socket import *
serverName = 'localhost'
serverPort = 8797
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
print ('The server is ready to receive')
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
print(sentence)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()
I am trying to exchange some string data between a Python Server (ideally, a Raspberry Pi with some device connected through GPIO) and a Java Client (again, the main target would be an Android app). The following code, anyway, is running on a standard local PC.
This is the code for the server, taken (and slightly modified) from here:
import socketserver
import datetime
class MyTCPHandler(socketserver.StreamRequestHandler):
def handle(self):
now = datetime.datetime.now()
answer = now
self.data = self.rfile.readline().strip()
print("Read!")
if str(self.data) == 'date':
answer = now.date()
elif str(self.data) == 'time':
answer = now.time()
self.wfile.write((str(answer)+"\n").encode('utf-8'))
print("Sent!")
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
print("Server is running on {}, port {}".format(HOST, PORT))
server.serve_forever()
The Java client is the following:
public class SocketTest {
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1", 9999);
PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out.println("date".getBytes());
String resp = in.readLine();
System.out.println("Received: " + resp);
} catch (IOException ex) {
Logger.getLogger(SocketTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
No exception is thrown whatsoever, it just gets stuck waiting for the response on the client side, and I can never see the "Read!" message on the server side.
The "date".getBytes() comes from somewhere on the net where I found that the Python sockets expect bytes (UTF-8), but in Java I'm sending strings directly, so it might be wrong.
Any help will be appreciated!
Turnes out, it was a flushing problem.
Apparently, the buffer is not flushed when the end of line is reached (which is how I was expecting it to behave).
Adding a simple out.flush() solved the problem.
I've set up a Raspberry Pi 3 and I want to make a program that sends data whenever a button is pushed on my breadboard. I have a Python server running on my RPi, and a Java client running on my Windows laptop. However, whenever I send data to my Java client, it receives the data, and then for some reason, the RPi server closes the program due to "broken pipe". However this cannot be true, because my Java program receives data from the Pi! The Java program then closes due to the Pi server closing. But from what I've read online, Python's "error 32: broken pipe" is triggered when the remote socket closes prematurely!
What's going on here? Why can't I keep my server running?
(PS: The data that my Java program receives is wrong, but it receives data nonetheless. I send "1\n", and I receive null.)
Here is the code for my RPi server program:
import RPi.GPIO as GPIO
from time import sleep
import atexit
import socket
import sys
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5, GPIO.IN)
GPIO.setup(7, GPIO.OUT)
def cleanup():
print("Goodbye.")
s.close()
GPIO.cleanup()
atexit.register(cleanup)
THRESHOLD= 0.3
host= sys.argv[1]
port= 42844
length= 0
def displayDot():
GPIO.output(7,True)
sleep(0.2)
GPIO.output(7,False)
def displayDash():
GPIO.output(7,True)
sleep(0.5)
GPIO.output(7,False)
try:
print("Initializing connection...")
s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverAddress= (host, 42844)
s.bind(serverAddress)
print("Connection initialized!")
print("Waiting for client...")
s.listen(1) #Puts the server socket into server mode
client, address= s.accept()
print(address)
while True:
if not GPIO.input(5):
length+= 0.1
GPIO.output(7,True)
s.sendall('1\n')
print("HELLO??")
else:
if length!=0:
if length>=THRESHOLD:
print("Dash") #displayDash()
else:
print("Dot") #displayDot()
s.sendall('0')
length= 0
GPIO.output(7,False)
except KeyboardInterrupt:
print("\nScript Exited.")
cleanup();
Here's the code for the Java client program:
import java.net.*;
import java.io.*;
public class MorseClient{
public static void main(String[] args) throws IOException{
String hostname= null; //Initialize
int portNumber= 0; //Initialize
try {
hostname= args[0];
portNumber= Integer.parseInt(args[1]);
}
catch(ArrayIndexOutOfBoundsException aiobe) {
System.err.println("ERROR. Please specify server address, and port number, respectively");
System.exit(1);
}
Socket redoSocket;
long initTime;
try(
Socket echoSocket= new Socket(hostname, portNumber);
PrintWriter out= new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in= new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdin= new BufferedReader(new InputStreamReader(System.in));
){
redoSocket= echoSocket;
System.out.println("Connection made!");
String userInput= "";
//Order of priority
//Connection time= 0
//Latency= 0
//Bandwidth= 1
redoSocket.setPerformancePreferences(0,0,1);
//Optimizes reliability
redoSocket.setTrafficClass(0x04);
echoSocket.setKeepAlive(true);
String returned= "";
while(true){
returned= in.readLine();
System.out.println(returned);
if(!(returned.isEmpty())){
System.out.println(returned);
System.out.println("YEP");
}
System.out.println(returned);
if(returned==null){
System.out.println("HAHA");
System.out.println("Attempting to reconnect...");
redoSocket= new Socket(hostname,portNumber);
System.out.println(redoSocket.isConnected());
}
}
}
catch(Exception e){
if(e instanceof ConnectException || e instanceof SocketException || e instanceof NullPointerException)
System.err.println("Connection closed by server");
else
System.err.println(e.toString());
}
}
}
The output for the Pi server is:
python ServerMorse.py 192.168.1.101
Initializing connection...
Connection initialized!
Waiting for client...
('192.168.1.14', 58067)
('192.168.1.14', 58067)
Traceback (most recent call last):
File "ServerMorse.py", in <module>
s.sendall('1\n')
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 32] Broken pipe
Goodbye.
And the output for the Java client:
java MorseClient 192.168.1.101 42844
Connection made!
null
Connection closed by server
Good lord, why are you writing a server with sockets? Use Flask.
http://flask.pocoo.org/
Also, pretty sure s should not be sending all. It should be like this:
conn, addr = server.accept()
conn.sendall(.... # <- this is what sends
Here is some sample code from a server I wrote with sockets once..might be useful:
def server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
address = ('127.0.0.1', 5020)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(address)
server.listen(1)
conn, addr = server.accept()
...
...
conn.sendall(response_ok(some_stuff))
...
conn.close()
(response_ok is a function I wrote)
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.
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