Hey there,
I am developing an TCP socket server in Java. The client(s) must connect to a webpage (in PHP)
Well, here come's my trouble.. They can connect to the specified host, but the server can't read the packets that the client send.
If I create the client in Java, it works 100%. Well, here are some snippets of my code. I hope someone have a answer for me. Because I'm stuck.
This is my little PHP script that sends:
<?php
set_time_limit(0);
$PORT = 1337; //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 = "wouter123"; //the text we want to send to the server
socket_sendto($sock, $text, strlen($message), MSG_EOF, '127.0.0.1', '1337');
//socket_write($sock, $text . "\n", strlen($text) + 1) //Writing the text to the socket
// or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000, PHP_NORMAL_READ) //Reading the reply from socket
or die("error: failed to read from socket\n");
echo $reply;
?>
The socket side is:
package com.sandbox.communication;
public class PacketHandler {
public String processInput(String theInput) {
String theOutput = null;
if (theInput == "wouter123") {
theOutput = theInput;
}else {
theOutput = "Cannot find packet. The output packet is " + theInput;
}
return theOutput;
}
}
And this little code connects to the PacketHandler:
PacketHandler ph = new PacketHandler();
while ((inputLine = in.readLine()) != null)
{
outputLine = ph.processInput(inputLine);
out.println(outputLine);
}
As you are using readLine on your input stream so make sure your clients are sending the data with linefeed.
From the javadocs
readLine() Reads a line of text. A line is considered to be terminated
by any one of a line feed ('\n'), a carriage return ('\r'), or a
carriage return followed immediately by a linefeed.
Related
I am doing a simple Java Client application which should communicate with Python Server. I can easily send a string to Python Server and print it in console, but when i'm trying to use received string in IFs it never get into IF statement even if it should.
Here is Java Client send msg code
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
if(msgToServer != null){
dataOutputStream.writeUTF("UP");
}
System.out.println(dataInputStream.readLine());
And Python Server code:
import socket
HOST = ''
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
print 'Socket now listening'
conn, addr = s.accept()
print 'Connected to: ' + addr[0] + ':' + str(addr[1])
data = conn.recv(1024)
if data == "UP":
conn.sendall('Works')
else:
conn.sendall('Does not work')
conn.close()
s.close()
print data
So when i send to Python Server "UP" it should send back to Java Client "Works", but i reveive "Does not work" and in Python Server the output data is: "UP"
Why it isn't go into if statement?
The JavaDoc of DataOutputStream#writeUTF(...) says:
First, two bytes are written to the output stream as if by the
writeShort method giving the number of bytes to follow
In you python code your data value will be prefixed with two bytes for the length of the string to follow.
i am working with socket programming and my server socket is in java and my client program is in php. here server.java is continuouly sending data(running on command prompt). when the connection is established i got the response from server to the client.php on the browser only one time.
here the problem is that, i want to continuously display the data on client.php(display on browser).
client.php
<?php
$host = "192.168.1.10";
$port = 4444;
$message = "Hello Server";
echo "Message To server :".$message;
while (true) {
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server :".$result ."<br>";
}
?>
It seems that your server implementation is not able to handle multiple client connections.
Try to call socket_create and socket_connect just once outside of the while loop
i found the solution. The server is continuously listening the client socket and sending the message also. just i need to display on the browser.Now solution: I am automatically refreshing the client.php socket. I don't no this is the right way to do this or not. But the output is getting right what i am expecting.
Client.php
<?php
$host = "192.168.1.10";
$port = 4444;
$message = "Hello Server";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
// send string to server
if($result) {
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
}
echo "Reply From Server :".$result ."<br>";
// close socket
//socket_close($socket);
$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 1; URL=$url1");
?>
You are recreating the socket all over again in the loop. When the socket is recreated the second time, the old connection seems not to have been properly removed, so it returns an error.
Just move your while loop above the socket_write call.
I tested this with nc listening to port 4444 using the script from command line and was able to communicate with the server.
Code of client:
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
while (true) {
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server :".$result ."\n";
}
?>
Server:
cat - | nc -l 172.16.1.1 4444
To be able to simply type in arbitrary Server responses.
I want to send a message with socket to an java server and it should response.
InputStreamReader inputStream = new InputStreamReader(server.getInputStream());
BufferedReader input = new BufferedReader(inputStream);
String clientSentence = input.readLine();
System.out.println(clientSentence);
This infinite, so I can't send a response to my php socket connection.
PHP:
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
$st="testSalt,broadcast";
$length = strlen($st);
socket_write($socket, $st, $length);
$resp = socket_read($socket, 1024);
Terminate strings from the PHP socket with a newline character to match the readLine statement of the Java server
$st = "testSalt,broadcast\n";
I don't know much about PHP, but it looks to me that if you send the contents of $st as-is, there won't be any newline character for the Java socket to read, and thus the input.readLine() call will hang until the Socket closes.
I'm trying to transfer simple message between PHP socket and JAVA socket. The php socket successfully sends the data and is waiting for Java servers response. But on the other hand Java server's socket is still waiting for the message from PHP.
Here is the Java Code:
ServerSocket s = new ServerSocket(4280);
Socket sock = s.accept();
System.out.println("Connected");
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
System.out.println("Reading");
String str = br.readLine();
System.out.println("Writing");
bw.write(str);
Output:
Connected
Reading
Here's the PHP code:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, "localhost", 4280);
socket_write($socket, "Hello");
echo socket_read($socket, 10);
socket_write($socket, "Lelo");
echo socket_read($socket, 10);
Output:
Browser: waiting for localhost
Two things that can usually cause a problem:
Java is utilizing the readLine() method but your not sending a linefeed and return in your PHP code.
Try also flushing on the PHP side.
Code:
Adding linefeed:
socket_write($socket, "Hello\r\n");
String str = br.readLine(); expect a \n which is not sent by the PHP program.
Add this :
socket_write($socket, "Hello\n" ); // <<<=== '\n' added
I am trying to read a string from php client socket in a java server socket. I am writing two strings in php socket client
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
socket_connect($this->socket, $this->host, $this->port)
$text = 'SGSA:PRINT:RECIBO';
socket_write($this->socket, $text, strlen($text));
$text = 'Mensagem para imprimir';
socket_write($this->socket, $text, strlen($text));
However when I read it in java like below
Socket clientSocket = server.accept();
InputStream in = clientSocket.getInputStream();
String msg;
try {
msg = IOUtils.toString( in );
} finally {
IOUtils.closeQuietly(in);
}
It reads two string together at once.
run-single:
SGSA:PRINT:RECIBOMensagem para imprimir
How can I read one string per time?