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
Related
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.
I`m trying to connect a Java Client with a Server in the same LAN, client and server are in two different PCs.
Here goes my Client Code,
import java.io.*;
import java.net.*;
public class Client{
public static void main(String[] args) throws Exception{
String ip = "192.168.0.103";
int port = 9999;
Socket s = new Socket(ip,port);
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String msgin = " ";
String msgout = " ";
while(!msgin.equals("end")){
msgout = br.readLine();
dout.writeUTF(msgout);
msgin = din.readUTF();
System.out.println("Mr.Client : "+msgin);
}
}
}
The Server PC has a IP of 192.168.0.103 .
Here is the Server code,
import java.io.*;
import java.net.*;
public class Server{
public static void main(String[] args) throws Exception{
System.out.println("Server started ... ... ");
ServerSocket ss = new ServerSocket(9999);
System.out.println("Waiting for client request ... ... ");
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String msgin = " ";
String msgout = " ";
while(!msgin.equals("end")){
msgin = din.readUTF();
System.out.println("Mr.Server : "+msgin);
msgout = br.readLine();
dout.writeUTF(msgout);
dout.flush();
}
}
}
Whenever I`m running these codes, the Server shows it is waiting for the Client but after running Client, the Client becomes frozen for unlimited time, stays stuck, no output.
To be mentioned, the Client is running on a Ubuntu machine and Server is on a Windows one.
When I ran the Client and Server in Windows PC using localhost, it worked without any issue.
Some clue would mean great help. Thank you.
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.
I would like to take text from a file and then send it to the server for it to capitalise before sending back to the client where it is printed out. How do I achieve this?
I can read one line and send that back to the client and I've managed to write multiple lines to the output stream (for the server to read) but I don't know what to do now..
I have a client that reads text from a file:
import java.io.*;
import java.net.*;
import java.util.Date;
public class Client
{
public static void main(String[] args)
{
try
{
// First create the input from keyboard
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Client Program");
// Next we need to find out the IP address and port number of the server
System.out.print("Enter IP Address of server: ");
String ip = input.readLine();
System.out.print("Enter port number of server: ");
String port_string = input.readLine();
// The port number needs to be an int, so convert the string to an int
int port = Integer.parseInt(port_string);
// Connect to the server
Socket sock = new Socket(ip, port);
// Create the incoming stream to read messages from
DataInputStream network = new DataInputStream(sock.getInputStream());
//Create the output stream to the client
DataOutputStream message = new DataOutputStream(sock.getOutputStream());
//Send message
//message.writeUTF("some text");
FileReader file = new FileReader("text.dat");
BufferedReader input_file = new BufferedReader(file);
// Loop until EOF
while (input_file.ready()){
// Read next line from the file
String line = input_file.readLine();
// Write line to server
message.writeUTF(line + "\n");
//System.out.println(line);
}
// Display our address
System.out.println("Address: " + sock.getInetAddress());
String line;
// Loop until the connection closes, reading from the network
while ((line = network.readUTF()) != null)
{
// Display the received message
System.out.println(line);
}
}
catch (IOException ioe)
{
// This is expected when the server closes the network connection
System.err.println("Error in I/O");
System.err.println(ioe.getMessage());
System.exit(-1);
}
}
}
And then a server that is supposed to take those strings and capitalise them:
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
{
public static void main(String[] args)
{
try
{
// First create the input from the keyboard
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server Program");
// Get the port to listen on
System.out.print("Enter port number to listen on: ");
String port_string = input.readLine();
// The port number needs to be an int, so convert the String to an int
int port = Integer.parseInt(port_string);
// Create a ServerSocket to listen on this address
ServerSocket server = new ServerSocket(port);
// Accept an incoming client connection on the server socket
Socket sock = server.accept();
// Create the output stream to the client
DataOutputStream network = new DataOutputStream(sock.getOutputStream());
//Create the incoming stream to read messages from
DataInputStream message = new DataInputStream(sock.getInputStream());
String newLine = inFromClient.readLine();
//Line to read
String line;
line = message.readUTF();
line = line.toUpperCase();
// Send message
network.writeUTF(newLine);
// Close sockets. This will cause the client to exit
sock.close();
server.close();
}
catch (IOException ioe)
{
System.err.println("Error in I/O");
System.err.println(ioe.getMessage());
System.exit(-1);
}
}
}
The problem is your server is reading the stream only once and closing the socket connection.
How will your server know you have finished sending the client data to the server socket ?
You should modify the server to listen to the port till you have finished sending the whole text. For that do something like -
String newLine;
while ( true )
newLine = inFromClient.readLine();
if (newLine.equalsIgnoreCase("END"))
{
break;
}
newLine = newLine.toUpperCase();
// Send message
network.writeUTF(newLine);
}
// Close sockets. This will cause the client to exit
sock.close();
server.close();
And from the client send "END" after all lines have been sent.
The easiest way is to use IOUtils from Apache Commons. IOUtils.readLines will return a list of Strings
Exact same question : Read/convert an InputStream to a String
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