Socket messaging between Java Client and Python Server - java

I try to create a Socket messager between a Java Client and Python Server. It works to send a message ("Testdata") from client to server and print it out. But after input and send a message from server to client, I get no output from client. The client 'freezes' and must be terminated.
What is the problem with my client input?
Terminal Server:
py socketServer.py
Connection from: ('127.0.0.1', 57069)
from connected user: Testdata
> Test
send data..
Terminal Client:
java socketClient
Testdata
Python-Server:
import socket
def socket_server():
host = "127.0.0.1"
port = 35100
server_socket = socket.socket()
server_socket.bind((host, port))
server_socket.listen(2)
conn, address = server_socket.accept()
print("Connection from: " + str(address))
while True:
data = conn.recv(1024).decode()
if not data:
break
print("from connected user: " + str(data))
data = input('> ')
conn.send(data.encode())
print("send data...")
conn.close()
if __name__ == '__main__':
socket_server()
Java-Client:
private static void socketTest(){
String hostname = "127.0.0.1";
int port = 35100;
try (Socket socket = new Socket(hostname, port)) {
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, false);
BufferedReader input =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
Scanner in = new Scanner(System.in);
String text;
do {
text = in.nextLine();
writer.print(text);
writer.flush();
System.out.println("from server: " + input.readLine());
} while (!text.equals("exit"));
writer.close();
input.close();
socket.close();
}
}

This is because python messages are not explicitly finished with \r\n like #carlos palmas says in this answer.

Related

Client-server message exchange - Sockets in Java

I'm trying to answer the clients message with an echo, but I am not figuring how to. My client sends a message, but then I reverse the papers and the program doesn't proceed (gets stuck in line
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
of the server). I guess it is about closing the inputstream, but when I do that, that closes the socket and I have no way to reuse it. I have managed do do this with readUTF and with socket.shutDownInput, but I want a easiest way - like close or flush, which I am not getting.
Client
public class SocketClient {
public static void main( String[] args ) throws IOException {
// Check arguments
if (args.length < 3) {
System.err.println("Argument(s) missing!");
System.err.printf("Usage: java %s host port file%n", SocketClient.class.getName());
return;
}
String host = args[0];
// Convert port from String to int
int port = Integer.parseInt(args[1]);
// Concatenate arguments using a string builder
StringBuilder sb = new StringBuilder();
for (int i = 2; i < args.length; i++) {
sb.append(args[i]);
if (i < args.length-1) {
sb.append(" ");
}
}
String text = sb.toString();
// Create client socket
Socket socket = new Socket(host, port);
System.out.printf("Connected to server %s on port %d %n", host, port);
// Create stream to send data to server
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// Send text to server as bytes
out.writeBytes(text);
out.writeBytes("\n"); // devia meter readline a null...
System.out.println("Sent text: " + text);
System.out.println(socket.getInetAddress().getHostAddress() + " " + socket.getPort());
//out.close();
//socket.shutdownOutput(); trials...
////////////////////////////////////////////
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("here");
// Receive data until client closes the connection
String response;
while ((response = in.readLine()) != null)
System.out.printf("Received message with content: '%s'%n", response); // here is where client doesn't proceed - he doesn't get the echo
Server
public class SocketServer {
public static void main( String[] args ) throws IOException {
// Check arguments
if (args.length < 1) {
System.err.println("Argument(s) missing!");
System.err.printf("Usage: java %s port%n", SocketServer.class.getName());
return;
}
// Convert port from String to int
int port = Integer.parseInt(args[0]);
// Create server socket
ServerSocket serverSocket = new ServerSocket(port);
System.out.printf("Server accepting connections on port %d %n", port);
// wait for and then accept client connection
// a socket is created to handle the created connection
Socket clientSocket = serverSocket.accept();
System.out.printf("Connected to client %s on port %d %n",
clientSocket.getInetAddress().getHostAddress(), clientSocket.getPort());
// Create stream to receive data from client
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Receive data until client closes the connection
String response;
while ((response = in.readLine()) != null)
System.out.printf("Received message with content: '%s'%n", response);
/////////////////////////////////////////////
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); // he doesn't reach here
System.out.println("here-serv");
System.out.println(clientSocket.getInetAddress().getHostAddress() + " " + clientSocket.getPort());
// Send text to server as bytes
out.writeBytes("echo");
I actually believe this problem has something with the readline from server, it is not getting a null - but the client sends a "\n"! Can you find my code mistake? Thanks

socket server not sending data to php client

I am trying to create a communication between a socket server in java and a php client however apparently no data is sent from server to client. I have tried plenty of methods for writing data to socket but none of those did work although i am able to send data from client to server.
Server side code
int port = 5566, maxConnections = 0;
int nrCon=0;
ServerSocket listener = new ServerSocket(port);
Socket server;
while((nrCon++<maxConnections)|| (maxConnections ==0)){
server = listener.accept();
BufferedReader in = new BufferedReader (new InputStreamReader(server.getInputStream()));
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( server.getOutputStream() ) );
//PrintWriter out = new PrintWriter(server.getOutputStream(), true);
//ObjectOutputStream oos = new ObjectOutputStream(server.getOutputStream());
//DataOutputStream os = new DataOutputStream(server.getOutputStream());
String line, data="";
while((line = in.readLine())!= null ){
System.out.println("wowowoowow");
data = data + line;
String[] coords = data.split(" ");
}
out.print("ROUTE DIJKSTRA: \n");
//out.flush();
//os.writeUTF("testetstets");
client side code
$PORT = 5566;
$HOST = "localhost";
$sock = socket_create(AF_INET, SOCK_STREAM, 0)
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT)
or die("error: could not connect to host\n");
socket_set_nonblock($sock);
if ( $_POST['v_lat']=="undefined" && $_POST['v_lng']=="undefined" ){
$text = "$sLng $sLat $dLng $dLat";
}else{
$vLat = $_POST['v_lat'];
$vLng = $_POST['v_lng'];
$text = "$sLng $sLat $vLng $vLat $dLng $dLat";
}
$sent = socket_write($sock, $text, strlen($text)+1);
$sock_err = socket_last_error($sock);
if ($sent === false) {
echo "could not send data to server\n";
break;
}else {
echo "sent ".$sent." bytes\n";
}
echo "sock error send: ".$sock_err." \n";
$result = socket_read ($sock, 2048);
$sock_err = socket_last_error($sock);
echo "sock err: ".$sock_err." \n";
echo "Reply From Server :".$result;
What i do get from sock_err call is the error code 10035 which is apparently for server not sending the data no matter how many socket writing data methods i tried.
I ran out of ideas.

data received on server from android app always null

I am trying to connect from a android emulator to a application on my desktop and send a line of text.
My app is able to connect to the server, but when ever i try to read data its always null
Server application running on my desktop:
ServerSocket ss = new ServerSocket(9001);
Socket cs = ss.accept();
if (cs.isConnected()) {
System.out.println("Client connected.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(cs.getInputStream()));
String str = reader.readLine();
System.out.println("Data:" + str);
Client application running in android app emulator:
InetAddress addr = InetAddress.getByName("10.0.2.2");
Socket socket = new Socket(addr, 9001);
if (socket.isConnected()) {
Log.d("APP", "socket connected");
}
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
String str = "this is a sample";
pw.write(str);
I can see that the isConnected function of the socket on both the client and server turns true.
But the Data printed on the server is always null.
Thanks
Try adding a flush call after the 'pw.write(str)' statement:
pw.flush();

socket.recv not working with non blocking

this is my python code.
Whenever i tries to send it a string it does not receive and times out after 10 seconds.
python server
import socket # Import socket module
import sys
import select
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 50001 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
a = []
b = []
s.listen(1) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
s.setblocking(0)
ready = select.select([s], [s], [s], 10)
while True:
if ready[0]:
data = s.recv(4096)
print data
print "reached"
print 'Got connection from', addr
c.send('Thank you for connecting \r\n') #all strings have to end with /r/n!!!
print "sent"
break;
c.close() # Close the connection
My Java Client
import java.net.*;
import java.io.*;
public class MTExample
{
public MTExample()
{
String sentence;
String modifiedSentence = "undefined";
try
{
//ceating the socket to connect to server running on same machine binded on port no 3000
Socket client = new Socket("127.0.0.1", 50001);
System.out.println("Client connected ");
//getting the o/p stream of that connection
PrintStream out = new PrintStream(client.getOutputStream());
//sending the message to server
System.out.print("Hello from client\n");
System.out.flush();
//reading the response using input stream
//BufferedReader in= new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//System.out.println(in.readLine());
//closing the streams
sentence = in.readLine();
sentence = "haha";
DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
outToServer.writeBytes(sentence + "\n");
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
modifiedSentence = inFromServer.readLine();
System.out.println(modifiedSentence);
System.out.println("FROM SERVER: " + modifiedSentence);
client.close();
in.close();
out.close();
}
catch(Exception err)
{
System.err.println("hi* err"+err);
}
}
public static void main(String a[])
{
new MTExample();
}
}
Is there something wrong with the non blocking method in Python? the Java client was working fine before i changed the blocking segement on python to be non blocking on the recv socket

Communication between python client and java server

My aim is to send a message from python socket to java socket. I did look out on the resource mentioned above. However I am struggling to make the Python client talk to Java server. Mostly because (End of line) in python is different from that in java.
say i write from python client: message 1: abcd message 2: efgh message 3: q (to quit)
At java server: i receive message 1:abcdefghq followed by exception because the python client had closed the socket from its end.
Could anybody please suggest a solution for a consistent talk between java and python.
Reference I used: http://www.prasannatech.net/2008/07/socket-programming-tutorial.html
Update: I forgot to add, I am working on TCP.
My JAVA code goes like this:(server socket)
String fromclient;
ServerSocket Server = new ServerSocket (5000);
System.out.println ("TCPServer Waiting for client on port 5000");
while(true)
{
Socket connected = Server.accept();
System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
while ( true )
{
fromclient = inFromClient.readLine();
if ( fromclient.equals("q") || fromclient.equals("Q") )
{
connected.close();
break;
}
else
{
System.out.println( "RECIEVED:" + fromclient );
}
}
}
My PYTHON code : (Client Socket)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 5000))
while 1:
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
if (data <> 'Q' and data <> 'q'):
client_socket.send(data)
else:
client_socket.send(data)
client_socket.close()
break;
OUTPUT::
ON PYTHON CONSOLE(Client):
SEND( TYPE q or Q to Quit):abcd ( pressing ENTER)
SEND( TYPE q or Q to Quit):efgh ( pressing ENTER)
SEND( TYPE q or Q to Quit):q ( pressing ENTER)
ON JAVA CONSOLE(Server):
TCPServer Waiting for client on port 5000
THE CLIENT /127.0.0.1:1335 IS CONNECTED
RECIEVED:abcdefghq
Append \n to the end of data:
client_socket.send(data + '\n')
ya..you need to add '\n' at the end of the string in python client.....
here's an example...
PythonTCPCLient.py
`
#!/usr/bin/env python
import socket
HOST = "localhost"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
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"
`
Now Here's the java Code:
JavaServer.java
`
import java.io.*;
import java.net.*;
class JavaServer {
public static void main(String args[]) throws Exception {
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);
}
}
`
Reference:Python TCP Client & Java TCP Server
here is a working code for the same:
Jserver.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Jserver{
public static void main(String args[]) throws IOException{
ServerSocket s=new ServerSocket(5000);
try{
Socket ss=s.accept();
PrintWriter pw = new PrintWriter(ss.getOutputStream(),true);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br1 = new BufferedReader(new InputStreamReader(ss.getInputStream()));
//String str[20];
//String msg[20];
System.out.println("Client connected..");
while(true)
{
System.out.println("Enter command:");
pw.println(br.readLine());
//System.out.println(br1.readLine());
}
}
finally{}
}
}
Client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 5000 # Reserve a port for your service.
s.connect((host, port))
while 1:
print s.recv(5000)
s.send("message processed.."+'\n')
s.close
I know it is late but specifically for your case I would recommend RabbitMQ RPC calls. They have a lot of examples on their web in Python, Java and other languages:
https://www.rabbitmq.com/tutorials/tutorial-six-java.html
for the people who are struggling with,
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
your can also use
.encode() to send the data

Categories

Resources