PHP socket Connection refused (Java server) - 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

Related

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.

how to send TCP Requests in java

I am using Sockets to connect using TCP and I want to make different calls. e.g. Get InputValue
I have these type of different requests which I want to make from already running server.
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
String func="Get inputvalue";
byte[] tRequest = encoder.string2bytes(func);
out.write(tRequest);
out.flush();
System.out.println("write done");
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
It says it connected as just connected printout got printed. Write done print is also printed but no data is returned and the program keeps on running.
If I use telnet then this same request call returns data successfully.
So the question is how to make TCP calls in java?
Update: I solved this by:
PrintWriter toServer =
new PrintWriter(client.getOutputStream(),true);
BufferedReader fromServer =
new BufferedReader(
new InputStreamReader(client.getInputStream()));
toServer.println("Get inputvalue\r\n");
String line = "";
System.out.println("Client received: ");
while ((line = fromServer.readLine()) != null) {
System.out.println(line);
}
but the program keeps on running in the while loop and prints nothing. how to check that response is ended?

Java TCP Socket Programming: Can not connect to remote host

I have a java program which accepts a http request from web browser and in response, program sends a text file contents to display in web browser. The program is working fine when I make request from browser which is installed on the same machine in which java code is running but when I make request from some other web browser which is not on the same machine as in which java code running, the program does not get any request.
This is how I make request from my web browser:-
http://localhost:port_number/
This is working fine...
This is how I make request from some other web browser which is not on my machine:
http://my_ip_address:port_number/
This is not working...
And this is my java code:-
while (true) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
try {
serverSocket = new ServerSocket(32768);
clientSocket = serverSocket.accept();
InetAddress ia = clientSocket.getInetAddress();
jTextArea1.append("Connected to : " + ia + "\n");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine, outputLine;
String s = (String) JOptionPane.showInputDialog(this, "Enter File Name : ");
File f = new File(s);
if (f.exists()) {
out.println("http/1.1 200 ok\r");
out.println("Mime version 1.1");
out.println("Content-Type: text/html\r");
out.println("Content-Length: " + f.length() + "\r");
out.println("\r");
BufferedReader d = new BufferedReader(new FileReader(s));
String line = " ", a;
while ((a = d.readLine()) != null) {
line = line + a;
}
out.write(line);
out.flush();
jTextArea1.append("File Delivered.\n");
d.close();
}
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
jTextArea1.append("Accept failed.");
System.exit(1);
}
}
This is not related to the code that you've written. You need to make your IP address publicly accessible. Here's is a related thread.
Check that you are indeed listening on 0.0.0.0:32768 and not 127.0.0.1:32768 or any other particulat IP (specially if you are connected to several network). Start a shell and use netstat -ano on Windows and netstat -anp on Unix or Mac.
Check that your firewall allows remote connection to the port 32768

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".

Simple Java Chat Program Help, Client Timesout when Connecting With Server

I'm creating a very simple Java chat program, using the Java TCP sockets. I'm new to socket programming and Java. I cannot connect with server, because every time the client connects to server it times out. Maybe, it is because I'm typing the wrong IP address——I don't know.
Here is the code for the Server:
try
{
int fport = Integer.valueOf(port.getText());
ServerSocket server = new ServerSocket(fport);
Socket socket = server.accept();
msg.append("\\n Server is listening to port:" + port.getText());
BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print(msgtxt.getText());
msg.append("\n\n" + input.readLine());
msg.append("\n\n" + Nombre.getText() + msgtxt.getText());
}
catch (Exception ex)
{
msg.setText("\n\n" + "Error:" + ex.getMessage());
}
Here is the code for the Client:
try
{
int iport = Integer.valueOf(port.getText());
int i1;
int i2;
int i3;
int i4;
i1 = Integer.valueOf(ip.getText());
i2 = Integer.valueOf(ip1.getText());
i3 = Integer.valueOf(ip2.getText());
i4 = Integer.valueOf(ip3.getText());
byte[] b = new byte[] {(byte)i1, (byte)i2, (byte)i3, (byte)i4 };
InetAddress ipaddr = InetAddress.getByAddress(b);
Socket sock = new Socket(ipaddr, iport);
BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
output.write(m.getText());
while(!input.ready()){}
msg.setText("\n\n" + input.readLine());
msg.setText("\n\n" + m.getText());
output.close();
input.close();
}
catch (Exception ex)
{
msg.setText("\n\n" + "Error: " + ex.getMessage());
}
verify that you can connect to the server using telnet (on windows you may need to install it as it's not installed by default anymore).
basically, open a connection to your server and see that it works:
telnet host port
if it works, maybe the problem is not in establising the connection but in waiting for a response from the server (add the exception to your question).
one note:
you can open a socket without creating the INetAddress as you did, just new Socket(hostname, port).

Categories