Communication between python client and java server - java

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

Related

Socket messaging between Java Client and Python Server

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.

How to make two separate mac terminals (command prompt windows) send text messages to each other without getting the "Address already in use" error?

I'm trying to create a text messaging program in java which will use two separate mac terminals (command prompt windows) to send and receive text messages to each other (UTF-8 strings) using two separate .java files in Eclipse (one is the server one is the client) (the two .java files have separate threads, one is called Server, the other is called Client)
The left window will be the client and the right window will be the server
The command line arguments for the server will be:
java DirectMessengerServer -l 3000
The command line arguments for the client will be:
java DirectMessengerClient 3000
The "-l" will be used later to differentiate between client and server later (ignore this for now)
The port number will be 3000.
Screenshot of error:
Code of client (DirectMessengerClient.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
public static void main(String args[]) throws IOException
{
Thread Client = new Thread ()
{
public void run ()
{
System.out.println("Client thread is now running");
ServerSocket server_socket = null;
Socket client_socket;
Socket smtpSocket = null;
DataOutputStream outputstream = null;
DataInputStream inputstream = null;
try
{
System.out.println("Try block begins..");
int port_number1= Integer.valueOf(args[0]);
ServerSocket listener = new ServerSocket(port_number1);
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + Integer.toString( port_number1 ) );
Socket socket = listener.accept();
client_socket= server_socket.accept();
BufferedReader reader= new BufferedReader(new InputStreamReader(client_socket.getInputStream(), "UTF8"));
PrintWriter output= new PrintWriter( client_socket.getOutputStream(), true );
outputstream = new DataOutputStream(smtpSocket.getOutputStream());
inputstream = new DataInputStream(smtpSocket.getInputStream());
String input_line= reader.readLine();
System.out.println( "Received from client: " );
System.out.println( input_line );
output.println( input_line );
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
//server.close();
// }
}
};
Client.start();
}
}
Code of Server (DirectMessengerServer.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerServer
{
public static void main(String args[]) throws IOException
{
Thread Server = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
ServerSocket server_socket = null;
Socket client_socket;
String message1;
for(int i = 0; i < args.length; i++)
{
if(args[i].equals("-l"))
{
try
{
System.out.println("Try block begins..");
int port_number1= Integer.valueOf(args[i+1]);
ServerSocket listener = new ServerSocket(port_number1);
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + Integer.toString( port_number1 ) );
Socket socket = listener.accept();
client_socket= server_socket.accept();
BufferedReader reader= new BufferedReader(new InputStreamReader(client_socket.getInputStream(), "UTF8"));
PrintWriter output= new PrintWriter( client_socket.getOutputStream(), true );
String input_line= reader.readLine();
System.out.println( "Received from client: " );
System.out.println( input_line );
output.println( input_line );
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
//server.close();
}
}
}
};
Server.start();
}
}
My question is: Is there a way to remove the "Address already in use" while having the same port number or perhaps I should use inetaddress or something instead? I am not sure how to make these two programs communicate (communication being to have text messages being outputted from one to the other, like text messaging between two phones), but that is the goal I would like to know how to accomplish
The problem is: you start the server and the port is getting occupy by the server just waiting for the client to come, then you start the client which is somehow (maybe a copy paste issue) creating a server too.. then the connection fails because the port is already used by your previously server...
remove the server part from DirectMessengerClient class

java client-server issue on client side (no System.out)

probably a noobish Q:
So i made a very simple single-threaded server/client model. Now when i execute the program in the eclipse IDE it shows me System.out's of the server and not the ones from the client.
When i press terminate, the System.out.println lines that were supposed to be generated by Client show up.
I'm struggling with this for days now.. Hopefully someone can help me out.
Thanks in advance!
SERVER:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args)
{
new Server();
}
public Server()
{
try
{
ServerSocket serverSocket = new ServerSocket(8000); //nieuw instantie van een ServerSocket
System.out.println("Waiting for clients..");
Socket socket = serverSocket.accept(); // lister for socket requests
while(true)
{
BufferedReader inputClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream clientOutput = new DataOutputStream(socket.getOutputStream());
String clientInput = inputClient.readLine();
System.out.println("Server: clientInput= : " + clientInput);
InetAddress hostAddress = InetAddress.getByName(clientInput);
String iPaddress = hostAddress.getHostAddress();
System.out.println("Server: IP = : " + iPaddress);
clientOutput.writeBytes(iPaddress);
clientOutput.flush();
}
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
CLIENT:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
new Client();
}
public Client()
{
try
{
Socket socket = new Socket("localhost", 8000);
DataOutputStream toServer = new DataOutputStream(socket.getOutputStream());
BufferedReader fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toServer.writeBytes("google.com" + '\n');
String ip = fromServer.readLine();
System.out.println("Client: "+ ip);
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
When you start a client and a server program, they will have 2 separate consoles. Only one is visible at a time in the "Console" view of Eclipse. That is why you only see the server's.
You can switch between the active consoles with the "Display Selected Console" icon (it's a monitor icon) and also see the active console list.
Also you have a full-duplex connection. Both the client and the server can read/write. You use a DataOutputStream - BufferedReader representation for a one-way communication which is WRONG.
DataOutputStream writes binary data, BufferedReader reads text (character) data.
You should use one of the following pairings:
DataOutputStream - DataInputStream and use writeUTF() and readUTF() methods
OR
PrintWriter - BufferedReader and use println() and readLine() methods
clientOutput.writeBytes(iPaddress);
clientOutput.write("\n".getBytes());
clientOutput.flush();
Just add these lines (second line) in your Server class.
Reason
In your Client class you are reading a line from buffer reader but you have not send any character from server indicating end of line. So in the second line we are writing new line character indicating end of line.
When you close the server, connection get reset and available input are read. Thats why your Client prints if you close the server.
Optionally if you only want to modify your Client class you can write these lines
char [] a = new char[100];
int length = fromServer.read(a);
System.out.println("Client: "+(new String(a)).substring(0,length));
Instead of these
String ip = fromServer.readLine();
System.out.println("Client: "+ ip);
Ok so after indexing the line with an '\n' and putting the line :
Socket socket = serverSocket.accept();
inside the while loop in stead of inside try{} i got rid of all my problems.
Thanks, now i'll try to multithread this thing!

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

BufferedReader give more null character in string while using with TCP Socket

My TCP Server is like this.
import java.net.*;
import java.io.*;
public class NetTCPServer {
public static void main(String[] args) throws Exception{
ServerSocket sock;
sock = new ServerSocket(1122);
if(sock == null)
System.out.println("Server binding failed.");
System.out.println("Server is Ready ..");
do{
System.out.println("Waiting for Next client.");
Socket clientSocket = sock.accept();
if(clientSocket!=null)
System.out.println("Clinet accepted. "+sock.getInetAddress().getHostAddress());
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
//DataInputStream in = new DataInputStream(clientSocket.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String name;
String pass;
String line;
name = in.readLine();
pass = in.readLine();
for(int i=0;i<name.length();i++)
System.out.print(name.charAt(i)+","); //see more null char are receiving here
System.out.println("");
System.out.println(name +" "+ name.length()+" \n" + pass+" "+pass.length());
}while(true);
}
}
And respective TCP Client is as follows.
import java.net.*;
import java.io.*;
public class NetTCPClient {
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getByName("localhost");
Socket sock;
sock = new Socket(addr,1122);
if(sock == null)
System.out.println("Server Connection failed.");
System.out.println("Waiting for some data...");
DataInputStream input = new DataInputStream(sock.getInputStream());
DataOutputStream output = new DataOutputStream(sock.getOutputStream());
String uname="ram";
String pass="pass";
output.writeChars(uname+"\n");// \n is appended just make to readline of server get line
output.writeChars(pass+"\n");
}
}
When i compiled both and the server is started and there after client is run, i get following output.
Server is Ready ..
Waiting for Next client.
Clinet accepted. 0.0.0.0
,r,,a,,m,,
ram7 pass9
The null character after each character receive is somewhat strange to me. To make me unable to compare the string with something stored in server.
What is those null characters and where does they come from.
You write characters but read lines of bytes. That won't work. If you're going to write characters, you need to read characters with precisely the same encoding. If you're going to write bytes, you need to read bytes. Specify your protocol precisely at the byte level and follow the specification in both the client and the server.
See this question for more information.

Categories

Resources