SocketServer Communication between java server and php client - java

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.

Related

Java client in socket

I have been looking for so long for a way to connect to a server created in Python using java.
Can anyone show me how to connect with java and how to send string? It is recommended that it also works on Android
My server in python:
import socket, time
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.bind(("160.07.08.49", 6784))
soc.listen(5)
(client, (ipNum, portNum)) = soc.accept()
while True:
print(client.recv(1024))
time.sleep(0.5)
My client in Java:
try {
Socket socket = new Socket("160.07.08.49", 6784);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
printWriter.write("Hello from java");
printWriter.flush();
printWriter.close();
}catch (Exception e) {e.printStackTrace();}
And I got an error from python when the Java client connected
print(soc.recv(20))
A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
Python echo server:
import socket
HOST = 'localhost'
PORT = 6784
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
Java client:
import java.io.*;
import java.net.Socket;
public class JavaClient {
public static void main(String [] args) {
String serverName = "localhost";
int port = 6784;
try {
Socket client = new Socket(serverName, port);
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The big difference is that I'm doing localhost to localhost. If you need to have the Python server available from outside of localhost, change the bind line to:
soc.bind(("0.0.0.0", 6784))
so that the server will listen on all available interfaces. Then have your Java client connect to the external IP of your server.

Can't read from socket

I have set up an pi zero running a simple python server script on my local network to respond to certain commands. I am trying to send those commands from an android java app. But when I try to read the reply from the command I have sent it seems like it skipes the line. Because "D/Sending data: Data has been send" is the last thing printed to the log.
This is the nested runnable class I am using to sent a command and then print the reply from the server:
private class SendData implements Runnable
{
private byte[] dataToSend;
private Socket socket;
private OutputStream outputStream;
private BufferedReader bufferedReader;
public SendData(Socket socket, byte[] dataToSend)
{
this.socket = socket;
this.dataToSend = dataToSend;
}
#Override
public void run()
{
try
{
outputStream = socket.getOutputStream();
outputStream.write(dataToSend);
Log.d("Sending data", "Data has been send");
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("Received", bufferedReader.readLine());
}
catch (IOException e)
{
Log.e("IOException Sending data", e.getMessage());
}
}
}
But when I try to read from the bufferedreader the applications just quits. While the server did sent a reply.
The thread gets started from from this method where "data" is a string.
if (socket != null)
{
Thread sendThread = new Thread(new SendData(socket, data.getBytes()));
Log.d("SocketClient send", "Starting send thread");
sendThread.start();
try
{
sendThread.join();
}
catch (InterruptedException e)
{
Log.d("SocketClient constructor", "Could not join");
}
}
else
{
Log.d("SocketClient send", "Socket is null");
}
Python script running on the pi:
import socket
import sys
from datetime import datetime
host = "192.168.4.1"
port = 12345
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(1)
def data_client(conn, ipStr):
while True:
data = conn.recv(2048)
reply = handle_command(data)
print "Command: %s" % data
if not data or data == "con_close":
print "Connection %s closed" % ipStr
break
conn.send(reply)
print "Send: %s" % reply
conn.close()
def handle_command(cmd):
if (cmd == "con_close"):
return cmd
elif (cmd == "get_time"):
return str(datetime.now())
else:
return "err_invalid_command"
while True:
print "listening:"
conn, addr = sock.accept()
print "Got connection from %s" % addr[0]
data_client(conn, addr[0])
If the receiver tries to read a line then the sender should have send one.
The receiver tries to read a line with readLine() but readLine() never returns as it waits for a newline char that has not been sent.

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.

TCP IP Client receives no input but packet sent from server

I have a java client program that sends a command to server and server sends back an acknowledgement and a response string.
My client program gets the input stream length from client socket as
0. But, I used wireshark to investigate. Wireshark logs show that the server has sent back a response to my ip. Somehow, my client is unable
to read it.
My Client
public class Client {
private static final String SERVER_ADDRESS = "192.168.64.79";
private static final int TCP_SERVER_PORT = 6669;
public void connect(String command) {
BufferedReader in;
try {
// Socket skt = new Socket("50.128.128.254", 6669);//ip,port
Socket clientSocket = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);// ip,port
System.out.println(" client Socket created ..Enter command : ");
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
String ToServer = command;
outToServer.println(ToServer);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.print("Received string : length "+clientSocket.getInputStream().available()+"\n response:");
// while (!in.ready()) {
// }
System.out.println(in.readLine()); // Read one line and output it
// System.out.print("'\n");
in.close();
clientSocket.close();
System.out.print("connection closed");
} catch (Exception e) {
System.out.print("Whoops! It didn't work!\n");
e.printStackTrace();
}
}
}
WireShark results:
9bytes of data sent from server to my client
Client output
Java client receives inputstream length 0

Java program not receiving/sending information to/from server/client

I'm trying to write a simple chat program with a server and a single client. I can connect them together just fine with port forwarding and they can each receive a single message. However, once they connect, I want to to be able to send and receive messages at the same time. For some reason this isn't happening at all. Here's my code.
Client:
// Client class
public class Client
{
public static void main(String [] args)
{
// Get server name, port number, and username from command line
String serverName = args[0];
int port = Integer.parseInt(args[1]);
String username = args[2];
try
{
// Print welcome message and information
System.out.println("Hello, " + username);
System.out.println("Connecting to " + serverName + " on port " + port);
// Create the socket
Socket client = new Socket(serverName, port);
// Print connected information
System.out.println("Just connected to " + client.getRemoteSocketAddress());
// Out to server
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
// Print message to server
out.writeUTF("Hello from " + client.getLocalSocketAddress());
// In from server
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
// Print message from server
System.out.println("Server says " + in.readUTF());
// Begin reading user input to send to the server
Scanner chat = new Scanner(System.in);
String lineTo;
String lineFrom;
// Keep the program open unless the user types endchat
while (!chat.nextLine().equals("endchat"))
{
// Read any messages coming in from the server
lineFrom = String.valueOf(in.readUTF());
System.out.println(lineFrom);
// Write any messages to the client
lineTo = chat.nextLine();
out.writeUTF(lineTo);
}
// Close the connection
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Server:
// Server class
public class Server extends Thread
{
private ServerSocket serverSocket;
private String username;
// Create server
public Server(int port, String username) throws IOException
{
serverSocket = new ServerSocket(port);
this.username = username;
}
// Keep running
public void run()
{
try
{
// Print info
System.out.println("Hello, " + username);
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
// Accept the client
Socket server = serverSocket.accept();
// To client
OutputStream outToClient = server.getOutputStream();
DataOutputStream out = new DataOutputStream(outToClient);
// From client
InputStream inFromClient = server.getInputStream();
DataInputStream in = new DataInputStream(inFromClient);
// Print info when connected
System.out.println("Just connected to " + server.getRemoteSocketAddress());
// Print message from client
System.out.println("Client says: " + in.readUTF());
// Print message to client
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress());
// Tell client they may begin chatting
out.writeUTF("You may now begin chatting! Type endchat to end the chat!");
// Start reading user input
Scanner chat = new Scanner(System.in);
String lineFrom;
String lineTo;
// Keep the program open as long as the user doesn't type endchat
while (!chat.nextLine().equals("endchat"))
{
// Read from client
lineFrom = String.valueOf(in.readUTF());
System.out.println(lineFrom);
// Send to client
lineTo = chat.nextLine();
out.writeUTF(lineTo + "\n");
}
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
}catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String [] args)
{
// Get port number and username from command line
int port = Integer.parseInt(args[0]);
String username = args[1];
try
{
// Create and start new Server
Thread t = new Server(port, username);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
EDIT: I added the newline character to my Server class when a message is sent. I'm now receiving the message in my Client class but the message I'm getting is in weird characters.
First separate out your read and write into distinct methods
i.e.
private String read(Server server){
// From client
InputStream inFromClient = server.getInputStream();
DataInputStream in = new DataInputStream(inFromClient);
.....
return message
}
private void write(Server server, String message){
OutputStream outToClient = server.getOutputStream();
DataOutputStream out = new DataOutputStream(outToClient);
......
}
Now use you main/run method to switch between read/write.
If the client writes, the it should wait for a read response and same with the server.
and you can do this while "endChat" is not true.
This is simplistic but it should get you going.
You can use something like this to send and receive messages at the same time.
new Thread(){
public void run(){
try{
while (!chat.nextLine().equals("endChat")){
System.out.println(in.readUTF());
}
}catch(Exception error){error.printStackTrace();}
}
}.start();
new Thread(){
public void run(){
try{
while (!chat.nextLine().equals("endChat")){
out.writeUTF(chat.nextLine());
}
}catch(Exception error){error.printStackTrace();}
}
}.start();

Categories

Resources