6

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

brainimus
11.1k14 gold badges44 silver badges65 bronze badges
asked Nov 15, 2010 at 14:23
4
  • EOL is EOL ('\n') - I think you'll need to post the bare minimum of code that creates your error Commented Nov 15, 2010 at 14:27
  • i forgot add, I am working on TCP. Commented Nov 16, 2010 at 5:18
  • Just a word of advice: String fromclient; is less efficient allocated there. Allocate it here: String fromclient = inFromClient.readLine(); Apart from that, the code is really nice. Commented Apr 20, 2011 at 18:08
  • @AmandeepChugh Please if any answer solve your problem, accept it. Commented Oct 1, 2014 at 10:00

5 Answers 5

8

Append \n to the end of data:

client_socket.send(data + '\n')
Mateen Ulhaq
27.9k21 gold badges122 silver badges155 bronze badges
answered Jan 19, 2011 at 7:27
Sign up to request clarification or add additional context in comments.

Comments

3

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

answered Apr 21, 2013 at 6:42

Comments

1

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 
answered Apr 23, 2016 at 8:24

Comments

0

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:

enter image description here

https://www.rabbitmq.com/tutorials/tutorial-six-java.html

answered Jan 22, 2017 at 21:47

Comments

0

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

Procrastinator
2,67445 gold badges31 silver badges37 bronze badges
answered Oct 5, 2022 at 10:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.