Connecting a Java Server with a Python Client - java

So here's the thing, I have a basic java server that sends back to the client what ever it receives from it. The client is written in python. I'm able to make the first connection as in the server sends the client a message confirming the connection. But when I want the client to send the server something is does nothing. I'm not sure if the problem with the client not sending or the server not receiving.
Here's the code for the server:
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter outs =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
outputLine = "Hello socket, I'm server";
outs.println(outputLine);
outs.println("I' connected");
while ((inputLine = in.readLine()) != null) {
outputLine = inputLine;
outs.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
} }
and here's the client :
import socket
HOST = "localhost"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print (socket.getaddrinfo(HOST,PORT))
buffer_size = 100
while True :
data = sock.recv(buffer_size)
print ('you recieved :' , data)
test = input('send here\n')
sock.sendall(bytes(test, 'utf-8'))
print ('you sent : ' , test)

In the Python client:
Your prompt contains a \n but the result from input does not? Try adding a \n to test before sending.

Related

Sending multiple strings over same TCP connection in Java?

I have been trying for hours and I just can't seem to get it done. I want to send two strings from TCP client to server, and return them both capitalized. The two strings are username and password:
Client code is:
public void actionPerformed(ActionEvent e) {
final String s1 =textPane.getText(); //retrieve username
final String s2=passwordField.getText();//retrieve password
//**************************************************************************
//after we have gotten the credentials, we have to send them to the server to check in the database
Socket clientSocket = null; //create new socket
String response=null; //create what is supposed to become the server's response
String response2=null;
try {
/**
* construct the client socket, specify the IP address which is here
* localhost for the loopback device and the port number at which a
* connection needs to be initialized.
*/
clientSocket = new Socket("localhost", 6789);
// These streams are for the same purpose as in the server side //
DataOutputStream outToServer = new DataOutputStream(clientSocket
.getOutputStream());
DataOutputStream outToServer2 = new DataOutputStream(clientSocket
.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
// read the user's input from the console. //
// send the sentence to the server: note the need to append it with
// an endline character //
outToServer.writeBytes(s1 + '\n'); //send username
outToServer.writeBytes(s2 + '\n'); //send password
// listen on the socket and read the reply of the server //
response2=inFromServer.readLine();
response = inFromServer.readLine();
} catch (UnknownHostException ex) {// catch the exceptions //
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("FROM SERVER: " + response); //print the response of the server
System.out.println("FROM SERVER: " + response2);
try {
// close the socket when done //
clientSocket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
Bulk of Server Code is:
while(true) {
// connection socket //
Socket connectionSocket;
try {
// accept connection on the connection socket from the welcome socket which is a server socket //
connectionSocket = welcomeSocket.accept();
// Get the input stream from the connection socket and save it in a buffer //
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
// Allocate an output stream to send data back to the client //
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
// Read the client sentence from the receive buffer //
clientSentence = inFromClient.readLine();
clientSentence2=inFromClient.readLine();
System.out.println("From user: " + clientSentence);
// capitalize the client's sentence, here the server does actions on the client's data //
capitalizedSentence = clientSentence.toUpperCase() + '\n';
capitalizedSentence2=clientSentence2.toUpperCase()+'\n';
if(clientSentence.equalsIgnoreCase("QUIT")){// close the socket if the server sends a quit message //
connectionSocket.close();
System.out.println("Connection Socket Quitting");
// Note that here the server will not exit or end up it will just close the connection with the client //
}
else outToClient.writeBytes(capitalizedSentence);// Send the capitalized sentence back to the client //
} catch (IOException ex) {
ex.printStackTrace();
}
}
What am I doing wrong? Can't one buffered reader accept two separate strings? How do I separate them later?
You haven't written back capitalizedSentence2 back to client that's why client is waiting at second readLine() as mentioned below:
response2 = inFromServer.readLine();
response = inFromServer.readLine();
put below line in your server side code in else part
outToClient.writeBytes(capitalizedSentence2);
It might solve your problem.

Socket Server will not receive properly

I am trying to make a socket server, I am connecting through putty to this server. Whenever I type "hi" it says "no" rather than "hi" which I want it to do. I found this on A java website. If you could tell me what I am doing wrong that would be great. Thanks!
int port = 12345;
ServerSocket sock = new ServerSocket(port);
System.out.println("Server now active on port: " + port);
Socket link = sock.accept();
System.out.println("Interface accepted request, IP: " + link.getInetAddress());
BufferedReader input = new BufferedReader(new InputStreamReader(link.getInputStream()));
PrintWriter output = new PrintWriter(link.getOutputStream(), true);
output.println("ISEEYOU");
String inputLine;
Thread.sleep(1500);
while((inputLine = input.readLine()) != null) {
if(inputLine.equals("hi")) {
output.println("hi");
}else{
output.println("no");
}
}
Your Java program is correct.
I've tried your code, just added System.out.printf("[%s]", inputLine); as first line in the while loop to ensure, what I get from putty.
I guess your problem is the protocol putty uses to connect. It worked with RAW for me. See below the session setting I've used:
EDIT:
According to your comment I added some code for a simple client, that reads the line from console, sends it to the server and prints the echo back to console.
public void Client() throws IOException {
// Client that closes the communication when the user types "quit"
Socket socket = new Socket("localhost", 8080);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
BufferedReader user = new BufferedReader(new InputStreamReader(System.in));
String line;
while(!(line = user.readLine()).equals("quit")) {
ps.println(line); // Write to server
System.out.println(reader.readLine()); // Receive echo
}
socket.shutdownOutput(); // Send EOF to server
socket.close();
}
The corresponding server would look like this:
public void server() throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
// Just read a line and echo it till EOF
String line;
while((line = reader.readLine()) != null) ps.println(line);
}
You might need to change the port I used here, if 8080 is already binded on your machine. Also you might want to have the server running on another computer then the client. In this case you need to change "localhost".

Send string to client upon command JAVA

So I am trying to have a sever sit and listen waiting for a connection from a client. The client sends over some string and the sever does some action based on whats received. Now what I would like to happen is the client sends over some command asking for data back and have the server get what it needs to and send the string back.
Not a big deal right? Well for some reason I can't get it working, my best guess is that its not closing the socket properly. I can't figure out why it wouldn't or what I am doing wrong.
Client
String data = "";
DataOutputStream outToServer = null;
BufferedReader input;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("GETDATA");
outToServer.flush();
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
data = input.readLine();
Log.d("ANSWER: ", data);
input.close();
} catch (IOException e) {
Log.d("Error: ", e.toString());
}
Server
ServerSocket listeningSocket = new ServerSocket(9008);
BufferedReader fromClient ;
PrintStream os;
while(true) {
Socket clientSocket = listeningSocket.accept();
ServerConnection clientConnection = new ServerConnection(clientSocket);
os = new PrintStream(clientSocket.getOutputStream());
fromClient= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
if(fromClient.readLine().equals("GETDATA")){
os.println("DATA");
os.flush();
clientSocket.wait();
clientSocket.close();
}
else{
clientConnection.run();
}
}
Any ideas?
here is your error
outToServer.writeBytes("GETDATA");
the right code is
outToServer.writeBytes("GETDATA\n");
as your using readline you should send a full line with line break

Debugging a socket communication program

I have 2 classes (Client and Server) used to implement simple communication in my application. My code is shown below:
Server:
public class Server {
public static void main(String[] ar) {
int port = 1025; // just a random port. make sure you enter something between 1025 and 65535.
try {
ServerSocket ss = new ServerSocket(port); // create a server socket and bind it to the above port number.
System.out.println("Waiting for a client...");
Socket socket = ss.accept();
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("enter meter id ");
String line = null;
while (true) {
line = in.readUTF(); // wait for the client to send a line of text.
System.out.println("client send me this id number " + line);
line = keyboard.readLine();
out.writeUTF(line);
out.flush();
//line = in.readUTF();
System.out.println("Waiting for the next line...");
System.out.println();
}
} catch (Exception x) {
x.printStackTrace();
}
}
}
Client:
public class Client {
public static void main(String[] ar) {
int serverPort = 1025;
String address = "localhost";
try {
InetAddress ipAddress = InetAddress.getByName(address); // create an object that represents the above IP address.
System.out.println(" IP address " + address + " and port "
+ serverPort);
Socket socket = new Socket(ipAddress, serverPort); // create a socket with the server's IP address and server's port.
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
// Create a stream to read from the keyboard.
BufferedReader keyboard = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
System.out.println("ClientConnected.");
System.out.println("enter meter id");
while (true) {
line = keyboard.readLine(); // wait for the user to type in something and press enter.
System.out.println("Sending this number to the server...");
out.writeUTF(line); // send the above line to the server.
out.flush(); // flush the stream to ensure that the data reaches the other end.
line = in.readUTF(); // wait for the server to send a line of text.
System.out
.println("The server was very polite. It sent me this : "
+ line);
System.out.println();
}
}
catch (Exception x) {
x.printStackTrace();
}
}
}
My problem is that while testing the program I do get communication between the client and server, but while debugging, with a break point on the out.flush line in Server.java, it does not go to the intended destination. This intended destination being the line line = in.readUTF(); of Client.java. Can anyone help me to solve this?
It is good practice to open the OutputStreams before the InputStreams, on your sockets, as said in this question.
This question also clarifies that.
What I suspect here is your client and server are running in two different JVM processes and java debugger cannot debug two JVM at the same time.

PHP/Java Sockets - Strange error?

Java code:
package servermonitor;
import java.io.*;
import java.net.*;
public class CommandListener extends Thread
{
public int count = 0;
public void run()
{
try
{
ServerSocket server = new ServerSocket(4444);
while(true)
{
System.out.println("listening");
Socket client = server.accept();
System.out.println("accepted");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("got reader");
String data = "";
String line;
while((line = in.readLine()) != null)
{
System.out.println("inloop");
data = data + line;
}
System.out.println("RECIEVED DATA: " + data);
in.close();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
count++;
out.write("gotcha: " + count + "\\n");
out.flush();
}
}
catch(IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
Java console (when I access the following PHP script):
listening
accepted
got reader
PHP code:
<?php
$PORT = 4444; //the port on which we are connecting to the "remote" machine
$HOST = "localhost"; //the ip of the remote machine (in this case it's the same machine)
$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT) //Connecting to to server using that socket
or die("error: could not connect to host\n");
$text = "Hello, Java!\n"; //the text we want to send to the server
socket_write($sock, $text, strlen($text) + 1) //Writing the text to the socket
or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000) //Reading the reply from socket
or die("error: failed to read from socket\n");
echo $reply;
?>
When I navigate to the PHP page, it loads forever.
Any ideas?
The Java side expects a newline in its input. You're not sending one, so readLine never finishes.
Also, readLine won't return null until the socket is closed or an exception occurs (I/O error for instance). You need to return some data as soon as you've read a line if your protocol works like that.
As it was told, you need to close socket to readLine returns null.

Categories