Terminate Java Socket SSL Connection at haproxy? - java

I am trying to write a Server<->Client based Software which encrypt the Data via SSL so that I dont have to handle the Encryption manually. For getting the Certificates I am using letsencrypt, so I have to create the Keystore manually from that Files every Time they renew. Because such manual Processes are not the best for using them in production I think of putting an haproxy in front of my Server and let this do the SSL Termination.
For what I tested this works somehow because the Client and Server can communicate with each other, but when I have a look with TCP Dump at the Port I see the Data being transfered unencrypted.
So is it principle possible to do it in this way with haproxy and do I miss something or should I stop thinking about it?
Here ist my Code for Client:
SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket)factory.createSocket("test.com", 9999);
socket.setEnabledProtocols(protocols);
socket.setEnabledCipherSuites(cipher_suites);
socket.startHandshake();
OutputStream socketoutstr = socket.getOutputStream();
OutputStreamWriter osr = new OutputStreamWriter(socketoutstr, "UTF-8");
BufferedWriter bw = new BufferedWriter(osr);
InputStream socketinstr = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(socketinstr, "UTF-8");
BufferedReader br = new BufferedReader(isr);
InstanceVariables.reset();
bw.write("1");
bw.newLine();
bw.flush();
and Server:
#Override
public void run() {
Socket socket = new ServerSocket(9999);
while (MainApplication.isRunning()) {
try {
Socket clientSocket = socket.accept();
Thread thread = new Thread(new Handler(clientSocket));
thread.start();
} catch (IOException e) {
System.out.println(e);
}
}
}
public class Handler implements Runnable {
private Socket clientSocket;
public Handler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
SystemOperations.load();
OutputStream socketoutstr = clientSocket.getOutputStream();
OutputStreamWriter osr = new OutputStreamWriter(socketoutstr, "UTF-8");
BufferedWriter bw = new BufferedWriter(osr);
InputStream socketinstr = clientSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(socketinstr, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String request = "";
request = br.readLine();
switch (request) {
case "1":
//Do Stuff here
}
} catch (IOException uhe) {
uhe.printStackTrace();
}
}
}

Related

Can't send multiple messages via socket

I'm trying to make a little chat system. I have a console and a client. Right now only the client need to send messages to the console. I can connect successfully to the server, and i can send one message from client to console. The trouble begins after sending the first message. When the first message i can't send any other messages.
I don't know if it's the console that won't read the message or the client that won't send the message. In this case how could i troubleshoot this?
public class ClientMainClass {
private static Socket socket;
public static void main(String args[]) {
try {
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
Scanner scanner = new Scanner(System.in);
System.out.println("Skriv dit username:");
String name = scanner.nextLine();
System.out.println("Du er logget ind som: " + name);
String input;
do{
input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
System.out.println("Du forlod serveren");
socket.close();
continue;
}else {
/*OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);*/
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
Date date = new Date();
String time = date.getDate()+"/"+date.getMonth()+":"+date.getHours()+":"+date.getMinutes();
//Send the message to the server
String message = time+ " - " + name + ": "+input;
printWriter.println(message);
System.out.println(message);
continue;
}
}while (!(input.equals("exit")));
} catch (Exception exception) {
exception.printStackTrace();
} finally {
//Closing the socket
try {
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
My server:
public class Main{
private static Socket socket;
public static void main(String[] args) {
try {
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
while(true) {
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
System.out.println(br.readLine());
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch(Exception e){}
}
}
}
To be clear. I can connect to the server. I can send one message from client to console, but no more than one message.
You never read a second line. Your Server accepts a connection, reads one line from that connection and then waits for a new connection, discarding everything that might arrive at the first connection.
Your client however sends all input using the first (and only) connection, which is absolutely correct.
This specific problem can be solved like this:
while(true) {
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while(true){
System.out.println(br.readLine());
}
}
This will cause your program to print everything arriving on that first connection, but it will never accept a second connection.
In order to handle multiple clients, you need a Thread to deal with each one.

Not printing files content in socket programming

I am naive to this socket programming. I am trying to print the content of the file present in the directory in the server's console but the server is not able to locate the file.
Here is my code:
myClient.java
import java.net.*;
import java.io.*;
public class myClient {
public static void main(String args[]){
Socket socket = null;
String hostName,command,fileName;
int port;
if(args.length == 0){
System.out.println("Error: command line arguments (hostname,port,command,"
+ "filename) not found.\nTry again...!!!");
System.exit(1);
}
hostName = args[0];
port = Integer.parseInt(args[1]);
command = args[2];
fileName = args[3];
try{
socket = new Socket(hostName,port);
System.out.println("Client Socket Created..!!");
// creating input and output streams to read from and write to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
if(command.equals("GET")){
System.out.println("Client: GET "+fileName+" HTTP/1.1\n");
bw.write(fileName);
String line = br.readLine();
while(line != null){
System.out.println("Server: "+line);
line = br.readLine();
}
}
if(command.equals("PUT")){
System.out.println("Client: "+fileName+" sent to server");
bw.write(fileName);
// pass the file contents
bw.flush();
System.out.println("Server: "+br.readLine());
}
}
catch(UnknownHostException uhe){
System.out.println("Unknown Host...!!!");
System.exit(1);
}
catch(IOException e){
e.printStackTrace();
}
finally
{
//Closing the socket
try{
socket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
myServer.java
import java.net.*;
import java.io.*;
public class myServer {
static Socket socket;
public static void main(String args[]){
try {
int port = Integer.parseInt(args[0]);
//String fileName = "";
ServerSocket server = new ServerSocket(port);
while(true)
{
System.out.println("Server started and listening on port "+port);
socket = server.accept();
System.out.println("received a connection :"+socket);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("Echo server 1.1\n");
bw.flush();
String line = br.readLine();
while(line != null){
bw.write("Echo: "+line);
bw.flush();
line = br.readLine();
}
}
} catch (IOException e) {
System.out.println("No conncetion established");
System.exit(0);
//e.printStackTrace();
}
finally
{
//Closing the socket
try{
socket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
Kindly help me out finding a solution to this. I have tried many examples browsing different websites but not get to the solutions.
System.out.println("Client: GET "+fileName+" HTTP/1.1\n");
bw.write(fileName);
You aren't writing a correct HTTP command to the server. You're only sending the filename, not a complete command such as the GET command you're printing to the console.
The line terminator in HTTP is specified as \r\n, not \n.
You're also making no attempt to implement other aspects of HTTP 1.1 correctly, such as content-length. If you're going to implement HTTP you need a good knowledge of RFC 2616.
If possible you should throw this away and use HttpURLConnection.

android.os.NetworkOnMainThreadException (client application android / serveur application java) (send string)(using emulator localhost) [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
the class of client in android application (using emulator localhost), sending a string to my java application (serveur) :
public class Client_socket extends MainActivity{
private static Socket socket;
public static void lance()
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket("127.0.0.3", port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String nom = "premiere";
String sendMessage = ism + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
the class of serveur in java application how recive my string :
what the ip and port can i use?, and how can i get my ip?
public class Server
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String nom = br.readLine();
System.out.println("Message received from client is "+nom);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
Make sure you execute network operations in a background thread:
new Thread(new Runnable() {
#Override
public void run() {
lance(); // call your network method here
}
}).start();

java Simple Server Client program

I'm trying to build a simple server client program, I'm trying to figure a way how to prompt the CLIENT if the server is down, or if the server is up and loses connection
Question: How can I prompt the client that he's disconnected because the Server shuts down or loses connection
SERVER
public class Server{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
System.out.println("Client has connected!");
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
CLIENT
public class Client{
private static Socket socket;
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
while(true)
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//System.out.println("You're now connected to the Server"); /*this should only print once */
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number;
number=input.next();
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (IOException exception)
{
//System.out.println("Server is still offline");/*This should only print once*/
}
How can I prompt the client that he's disconnected because the Server shuts down or loses connection?
You can use the catch block to prompt the client in Client class which will be executed when IOException occurs
} catch (ConnectException e) { //When the connection is refused upon connecting to the server
//promt the user here
System.out.println("Connection refused");
break; //to quit the infinite loop
} catch (IOException e) { //when connection drops, server closed, loses connection
//promt the user here
System.out.println("Disconnected from server");
break; //to quit the infinite loop
}

ServerSocket accept continues to block

I'm having some trouble simulating a connection to my Server Socket, accept seems to continue blocking as it doesn't "see" the connection.
Here's some simplified code
#Test
public void testPDMServerThread() {
try {
ServerSocket serverSocket = new ServerSocket(0);
int port = serverSocket.getPort();
Socket clientSocket = new Socket("localhost", port);
PrintWriter clientRequest = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader serverResponse = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
serverThread = new ProducerMonitorServerThread(serverSocket.accept());
clientRequest.write("Hi!");
serverThread.start();
System.out.println("Server says: " + serverResponse.readLine());
assertEquals("RUNNABLE", serverThread.getState().toString());
} catch (IOException e) {
}
}
And here's the thread where the server should respond
public class ProducerMonitorServerThread extends Thread {
private Socket socket;
public ProducerMonitorServerThread(Socket socket) {
super("PDM");
this.socket = socket;
}
#Override
public void run() {
try {
PrintWriter serverResponse = new PrintWriter(socket.getOutputStream(), true);
BufferedReader clientRequest = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String serverInput, clientOutput;
while((serverInput = clientRequest.readLine()) != null) {
clientOutput = "Bye!";
System.out.println("Client says: " +serverInput);
serverResponse.write(clientOutput);
}
serverResponse.close();
clientRequest.close();
socket.close();
} catch (IOException e) {
}
}
}
It never seems to get past this line which is why I think accept is not seeing the connection
serverThread = new ProducerMonitorServerThread(testServer.accept());
I'm sure there's something fundamental that I'm just not seeing.
First of all, you should not ignore exceptions like you're doing.
The problem is not with accept. The problem is that the server uses readLine(), and the client never sends any EOL character, and never closes the socket. So the server is blocked waiting for an EOL to appear in the reader. The same is true for the client: it uses readLine() and the server never sends any EOL.
Use a debugger. It will help you find the cause of such problems.

Categories