PHP to Java - Sockets - java

I am trying to communicate from php to java using sockets. I have the following java code:
private static ServerSocket socket;
private static Socket connection;
private static String command = new String();
private static String responseStr = new String();
private static int port = 2500;
public static void main(String args[]) {
System.out.println("Server is running.");
try {
socket = new ServerSocket(port);
while (true) {
connection = socket.accept();
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
DataOutputStream response = new DataOutputStream(connection.getOutputStream());
BufferedReader input = new BufferedReader(inputStream);
command = input.readLine();
response.writeBytes(responseStr);
response.flush();
}
} catch (IOException e) {
System.out.println("Fail!: " + e.toString());
}
}
I have the following PHP code:
<?php
$socket = stream_socket_server("tcp://192.168.0.10:2500", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
fclose($conn);
}
fclose($socket);
}
I start the java app, which starts fine, When I run the php, I get the following error:
An attempt was made to access a socket in a way forbidden by its access permissions. (0)
I have searched Google and have tried all the solutions I could find although nothing has worked. I have restarted both machines and disabled the firewall, neither worked.
I am not sure where to go from here.
[update from comment:]
192.168.0.10 is the machine with the java app and web server on it. I am connecting from another machine 192.168.0.7

You can only can create a socket on the machine were the code is running on.
So if the PHP code is run on 192.168.0.7, then do:
$socket = stream_socket_server("tcp://192.168.0.7:2500", $errno, $errstr);

Related

PHP Client Socket blocks reading after write

I am programming a server socket for java that takes data from a client socket, processes them and sends a response back.
At the current state I am able to send data and process it, but unfortunately I wasn't able to figure out how to send the processed data from the server socket to the client socket. I already tried using the example provided from php.net, but that just somehow just blocks the sending of my data. I also tried to only read or write and that worked like a charm.
My server socket (java) looks as follows:
public class TcpListener {
public static String clientSentence;
private static ServerSocket serverSocket;
public static void main(String argv[]) throws Exception{
serverSocket = new ServerSocket(49654);
Socket connectionSocket = serverSocket.accept();
while(true)
{
//read
int reportId = read(connectionSocket);
//write
write(connectionSocket, reportId);
}
//connectionSocket.close();
}
public static int read(Socket connectionSocket) throws IOException{
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
Report r = new Report(clientSentence);
int reportId = r.main();
inFromClient.close();
return reportId;
}
public static void write(Socket connectionSocket, int id) throws IOException{
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true);
System.out.println(id);
outToClient.println(id);
outToClient.flush();
outToClient.close();
}
}
and my client socket (php):
set_time_limit(0);
ob_implicit_flush();
$host = "localhost";
$port = 49654;
if (($socket = socket_create(AF_INET, SOCK_STREAM, 0)) === false) {
echo "\nsocket_create() failed: reason: " . socket_strerror(socket_last_error());
} else {
echo "\nAttempting to connect to '$host' on port '$port'...\n";
if (($result = socket_connect($socket, $host, $port)) === false) {
echo "socket_connect() failed. Reason: ($result) " . socket_strerror(socket_last_error($socket));
} else {
socket_set_nonblock($socket);
echo "Sending data...\n";
$sresult = socket_send($socket, $message."\r\n", strlen($message), MSG_DONTROUTE);
if ($sresult === false) {
$errorcode = socket_last_error($socket);
$errormsg = socket_strerror($errorcode);
die("error sending data. " . $errormsg. "($errorcode)");
}
echo "OK\n";
echo "Reading response:\n\n";
while(socket_recv ( $socket , $buf , 2045 , MSG_WAITALL ) === FALSE){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
echo $buf;
}
echo "close";
socket_close($socket);
}
The following error message is being displayed:
Warning: socket_recv(): unable to read from socket [10045]: The attempted operation is not supported for the type of object
referenced. <b>D:\xampp\htdocs\api\select\getApps.php</b> on line <b>75</b><br />
Could not receive data: [10045] The attempted operation is not supported for the type of object referenced.
Where line 75 is the while loop.
I would appreciate any help on how to fix my problem.

Java client and python server connection

i am working on an app in android studio and basiclly i need that whenever i clicked a specific button it will create a connection between the java client and python server.
I first checked when u enter the page\activity of the specific button if there is a wifi connection in the phone.
It works fine. then i tried to do this and it didnt work (Important to say that the current code make my phone and my app crash and stop)
simple server:
HOST = '192.168.1.21'
PORT = 9000
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
client_socket, client_address = server_socket.accept()
print 'Connect with ' + client_address[0]
data = client_socket.recv(1024)
print "data :"
print data
print " end"
if data == HOST+"/n":
print 'hi'
else:
i = 0
while i < 15:
print i
i += 1
client_socket.close()
server_socket.close()
if __name__ == '__main__':
main()
this is just to check a connection. it might look strange because of the host +/n in the if . i recently chenged it because i am new to java and dont know how the data is sent. but that is not the problem rn.
public void ButtonClicked(View view) {
EditText editText = findViewById(R.id.edit_text);
final String ip = editText.getText().toString();
Toast.makeText(this, ip, Toast.LENGTH_SHORT).show();
try {
InetAddress host = InetAddress.getByName(ip);
final Client client = new Client(host, 9000);
new Thread(new Runnable() {
public void run() {
try {
client.send(ip);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
client.send(ip);
}
catch (IOException e) {
System.out.println("Caught Exception: " + e.toString());
}
i read that in android studio 3.0 u need to create a thread when u send data.
the client class that u see here :
public class Client
{
private Socket socket = null;
private BufferedReader reader = null;
private BufferedWriter writer = null;
public Client(InetAddress address, int port) throws IOException
{
socket = new Socket(address, port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
}
public void send(String msg) throws IOException
{
writer.write(msg, 0, msg.length());
writer.flush();
}
public String recv() throws IOException
{
return reader.readLine();
}
}
it might be just a simple thing that i dont know of but those are the codes and i cant connect to the server. i figured out that the server works fine because if im connecting from the phone to 192.168.1.21 on the net i receive the connection and it does thw little while.
ty for the help - i would like to get the simplest fixes because im new to java.(sorry if there where grammer\ spelling mistakes)
Edit- logcat for the crash
At the end of your log it says NetworkOnMainThread. In your code there is a line client.send(ip) below your seperate thread which is executed at the main thread.

SocketServer Communication between java server and php client

I am trying to establish communication between a SocketServer (Server) in Java and a Socket (Client) in php.
The client is able to connect to host, the client is able to send a message and the server reads the message successfully. But the problem arises when the SocketServer writes to the Client, the client does not receive the message from the server.
I have read the other questions on the same scenario (java-php socket communication) but i just can't seem to find what is causing the problem.
If i use a Java Socket as a client the communication works perfectly both ways.
The Server :
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
protected ServerSocket socket;
protected final int port = 9005;
protected Socket connection;
protected String command = new String();
protected String responseString = new String();
public void init(){
System.out.println( "Launching Server: " );
try{
socket = new ServerSocket(port);
while(true)
{
// open socket
connection = socket.accept();
System.out.println( "Client Connected " );
// get input reader
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
BufferedReader input = new BufferedReader(inputStream);
// get input
command = input.readLine();
// process input
System.out.println("Command: " + command);
responseString = command + " MC2 It Works!";
// get output handler
PrintStream response = new PrintStream(connection.getOutputStream());
// send response
response.println(responseString);
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
The Client :
class Client {
private $address;
private $port;
public function __construct($address, $port){
$this->address = $address;
$this->port = $port;
$this->init();
}
private function init(){
//create socket
if(! $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'))){
$this->showError("socket create");
};
//establish connection
socket_connect($socket, $this->address, $this->port);
//write to server
$message = "I am a client";
socket_write($socket, $message, strlen($message)); //Send data
echo "Listening to Server\n";
//read from server
if(!$reponse = socket_read($socket, 2048, PHP_NORMAL_READ)){
$this->showError("socket read");
}
//print response
echo "Response from server------------------\n";
echo $reponse;
socket_close($socket);
}
private function showError($message){
echo ("Error: ".$message);
exit(666);
}
}
$address="localhost";$port=9005;
echo "Testing Client Server\n";
$client = new Client($address, $port);
Could someone please guide me to what could be the problem here ?
In server side, the code expects a line(terminated with linefeed), in php You send
socket_write($socket, $message, strlen($message));
Please check the data you send accordingly making sure that you send the linefeed character.

testing a client server

I wrote a server that listens for client messages, it's a variation of http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html. I wrote them both in eclipse as java classes in the same project. To test it I have a client class with a main that starts the server and then sends messages to it. When I run it the program just hangs at serverSocket.accept(); according to the javadoc for ServerSocket accept is not asynchronous? That would explain the hanging, but then how does the tutorial code work then?
UPDATE - here is my working code:
Here is the working code:
MyServer.java
/*imports neglected for brevity */
public class MyServer {
public static final String hostname = "localhost";
public static final int portNum = 4444;
ServerSocket serverSocket;
BufferedReader serverReader;
File serverLog;
FileWriter fw;
BufferedWriter serverWriter;
Socket clientSocket;
public static void main(String[] args) {
MyServer server = new MyServer(portNum);
// start the server so it can listen to client messages
server.start();
}
public MyServer(int portNum) {
try {
// endpt for server side, used to listen for client socket
serverSocket = new ServerSocket(portNum);
/* have server socket listen for connection, return client socket.
* serverSocket can now talk to clientSocket
*/
clientSocket = serverSocket.accept();
// server writes messages to this log
serverLog = new File("ServerLog.txt");
if(!serverLog.exists())
serverLog.createNewFile();
fw = new FileWriter(serverLog.getAbsoluteFile());
serverWriter = serverWriter = new BufferedWriter(fw);
/* server reads from this stream that is populated by the client's
* OUTPUT stream/client socket's INPUT stream
*/
serverReader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream())
);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void start() {
String clientMsg;
try {
while((clientMsg = serverReader.readLine()) != null) {
if(clientMsg.startsWith("exit")) {
break;
}
serverWriter.append(clientMsg);
}
serverWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MyClient.java
public class MyClient {
public static final String hostname = "localhost";
public static final int portNum = 4444;
public static void main(String[] args) {
String msg = "message 1";
try {
// server is listening on http://localhost:4444
Socket serversSocket = new Socket(hostname, portNum);
PrintWriter clientOut = new PrintWriter(serversSocket.getOutputStream(), true);
// send first message
clientOut.println(msg);
msg = "message 2";
// send second message
clientOut.println(msg);
msg = "exit";
// this will stop the server
clientOut.println(msg);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
If you go through the tutorial it creates two applications one with client one with server.
You cannot create a variation like this as, when you call the constructor, your whole application blocks in clientSocket = serverSocket.accept();.
If you insist on creating a single application for whatever reason, you can do multithreading. But I do not see any reason why you would want to do that.
The tutorial assumes you are not running them in the same program. If you must run them in the same program, then start your server in a separate thread.
if you have an android phone you can test this with the app TCP socket
make sure you PortForward the port the server is listening to.
some isp also block ports so make sure with your isp that all ports are open
trust me broke my head on this one :)
http://docs.oracle.com/javase/6/docs/api/java/net/ServerSocket.html
also make sure your server has the public ip and not local ip
if you test this localy then the code above is fine if not you will need to add
bind(SocketAddress endpoint)
/*Binds the ServerSocket to a specific address (IP address and port number).*/
you can find your ip by typeing in google: whats my ip

Socket Connection on Java, specify IP

I'm working on a program where multiple clients need to interact with a remote server.
I've tested it locally and everything's ok (sort of, more on that later), but I can't understand how to set a remote IP.
I read Socket's API and also InetAddress' API. Is this the right way to do it? How does Java deal with IPs? There are not just simple Strings as on the localhost case, am I right?
This is my code:
Client:
public class Client {
final String HOST = "localhost";
final int PORT = 5000;
Socket sc;
DataOutputStream message;
DataInputStream istream;
public void initClient() {
try {
sc = new Socket(HOST, PORT);
message = new DataOutputStream(sc.getOutputStream());
message.writeUTF("test");
sc.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Server:
public class Server {
final int PORT = 5000;
ServerSocket sc;
Socket so;
DataOutputStream ostream;
String incomingMessage;
public void initServer() {
try {
sc = new ServerSocket(PORT);
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
}
BufferedReader input;
while(true){
try {
so = new Socket();
System.out.println("Waiting for clients...");
so = sc.accept();
System.out.println("A client has connected.");
input = new BufferedReader(new InputStreamReader(so.getInputStream()));
ostream = new DataOutputStream(so.getOutputStream());
System.out.println("Confirming connection...");
ostream.writeUTF("Successful connection.");
incomingMessage = input.readLine();
System.out.println(incomingMessage);
sc.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
Also, I'm dealing with some troubles on my local tests.
First of all, some times I get the following result:
Waiting for clients...
A client has connected.
Confirming connection...
Error: Software caused connection abort: recv failed
Though some other times it works just fine. Well, that first connection at least.
Last question:
When I try to send a message from the server to the client, the program enters in an infite loop and need to be closed manually. I'm adding this to the code to do so:
fromServerToClient = new BufferedReader(new InputStreamReader(sc.getInputStream()));
text = fromServerToClient.readLine();
System.out.println(text);
Am I doing it right?
Thanks.
Instead of using
String host = "localhost";
you can use something like
String host = "www.ibm.com";
or
String host = "8.8.8.8";
this is how you would usually implement a Server:
class DateServer {
public static void main(String[] args) throws java.io.IOException {
ServerSocket s = new ServerSocket(5000);
while (true) {
Socket incoming = s.accept();
PrintWriter toClient =
new PrintWriter(incoming.getOutputStream());
toClient.println(new Date());
toClient.flush();
incoming.close();
}
}
}
And following would be As Client:
import java.util.Scanner;
import java.net.Socket;
class DateClient {
public static void main(String[] args) throws java.io.IOException
{
String host = args[0];
int port = Integer.parseInt(args[1]);
Socket server = new Socket(host, port);
Scanner scan = new Scanner( server.getInputStream() );
System.out.println(scan.nextLine());
}
}
You should consider doing this in threads. Right now multiple users can't connect to the server at once. This means that they have to queue for connection to the server resulting in very poor performance.
Normally you receive the client and instantiate a new thread to handle the clients request. I only have exampls in C# so i won't bother you with that, but you can easily find examples on google.
eg.
http://www.kieser.net/linux/java_server.html

Categories

Resources