SSLSocket getOutputStream() blocks after handshake - java

I am opening an SSLSocket on the client side to connect to the server.
But trying to get the socket.getOutputStream() blocks the code, without outputting any errors.
I am flushing both streams, but it still doesn't work.
Server:
SSLSocket socket = (SSLSocket) serverSocket.accept();
socket.setUseClientMode(false);
try{
socket.setSoTimeout(0);
socket.setKeepAlive(true);
socket.addHandshakeCompletedListener(handshakeCompletedEvent -> {
try{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.println("Setup"); writer.flush();
while(running){
if(!socket.isConnected() || socket.isClosed()){
disconnect();
return;
}
for(Iterator<String> pendingIterator = pendingMessages.iterator(); pendingIterator.hasNext();){
String message = pendingIterator.next();
pendingIterator.remove();
writer.println(message); writer.flush();
}
//Auto decrypt when message arrives, but no thread blocking
if(reader.ready()){
String line = reader.readLine();
System.out.println(line);
}
}
}catch(Exception e){
e.printStackTrace();
}
});
socket.startHandshake();
}catch(Exception e){
e.printStackTrace();
disconnect();
}
Client:
socket.addHandshakeCompletedListener(new HandshakeCompletedListener(){
#Override
public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent){
try{
Log.i("Update", "Did handshake");
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.flush();
Log.i("Update", "Writer");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i("Update", "Reader");
while(isRunning){
try{
writer.println("Test");
writer.flush();
Log.i("DATA", "DATA SENT");
}catch(Exception e){
e.printStackTrace();
}
}
writer.close();
reader.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
socket.startHandshake();

You are misusing the handshake completed listener. Its purpose is to let to check he peer certificate, negotiated cipher suite, etc. Not to carry out the transaction. Remove it all and put it inline. You don't need even to call startHandshake(). It will happen automatically on the first I/O.

Related

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.

BufferReader.readline() block PrinterWriter.println()

After creating socket connection in Android App, i can't write in buffer after reading.
This is an example for establishing connection with my Server:
//...
try{
socket = new Socket(IP, Port);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
//ask for connection
out.println(req1);
//server send me a nonce
result=in.readLine().toString();
//encrypting nonce with specific alghorithm
passwd=Password.get_Passwd(result);
//sending password
out.println(passwd); //here out.println doesn't write
//...
} catch (IOException e){
e.printStackTrace();
} finally {
try {
socket.close();
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//...
So can any one help me solving this problem. Thanks.

how do i write on server and read on android

i want to create a printwriter in my java server and a buffertreader in my android code. right know i can send a message from my android and read it on my java compiler but i want to do the oppsite aswell. read on android and write on server. do i need two applications for that because i dont know if i can just put it in between try i each code?
android code:
try {
client = new Socket("10.0.2.2", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
java server:
while (true) {
try {
clientSocket = serverSocket.accept(); //accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
thank you for taking your time to read my problem
Yes you can create two way communication between them, all you have to do is open an InputStream on the client side (Android) and Open an OutputStream on the Java Server Side, it can be achieved in the following manner:
android code:
try {
client = new Socket("10.0.2.2", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
InputStream in = client.getInputStream();
byte data[] = new byte[1024]
in.read(data); ///perform your reading operation here
client.close(); //closing the connection
} catch (UnknownHostException e) {
java server:
while (true) {
try {
clientSocket = serverSocket.accept(); //accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
pw.write(new String("write data here"));
pw.flush();
pw.close();
clientSocket.close();
} catch (IOException ex) {

Android how to reuse Socket?

how to reuse TCP Socket connection(possible setReuseAddress(true), but not work for me) for download multiple files from Server(Apache, HTTPD) in on connection without disconnect(and connect again).
My code below..
public class ClientThread implements Runnable {
public void run() {
try {
Log.d("ClientActivity", "C: Connecting...");
SocketAddress sockaddr = new InetSocketAddress(serverIpAddress, SERVERPORT);
socket = new Socket();
socket.setReuseAddress(true);
socket.setKeepAlive(true);
socket.setSoLinger(true, 3000);
socket.connect(sockaddr);
if (socket.isConnected()) {
DataInputStream input = new DataInputStream(socket.getInputStream());
PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
output.println("GET /way/images/profile/1231 HTTP/1.1");
output.println("Host: 192.168.1.2");
output.println("User-Agent: Java");
output.println("Accept: */*");
output.println("Connection: Keep-Alive");
output.println("");
output.flush();
String line;
File file = new File("/sdcard/aaa.png");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOut = new FileOutputStream(file);
System.out.println("Getting first file");
while ( (line = input.readLine()) != null ) {
System.out.println(line);
fileOut.write(line.getBytes());
}
System.out.println("First file finished");
fileOut.flush();
fileOut.close();
output.println("GET /way/images/profile/1231 HTTP/1.1");
output.println("Host: 192.168.1.2");
output.println("User-Agent: Java");
output.println("Accept: */*");
output.println("Connection: Keep-Alive");
output.println("");
output.flush();
file = new File("/sdcard/aaa1.png");
if (!file.exists()) {
file.createNewFile();
}
fileOut = new FileOutputStream(file);
System.out.println("Getting second file");
while ( (line = input.readLine()) != null ) {
System.out.println(line);
fileOut.write(line.getBytes());
}
System.out.println("Second file finished");
fileOut.flush();
fileOut.close();
input.close();
output.close();
}
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
finally {
try {
Log.d("ClientActivity", "Socket: Closed.");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Thanks...
setReuseAddress(true) prior to binding the socket allows the socket to be bound even though a previous connection is in a timeout state.
documentation of setReuseAddress
I don't see sense in directly using socket for HTTP communication. I use HttpURLConnection. Works without problems in most cases.

java socket programming problem

what's wrong with my code?
sorry about my bad English
package sockettest;
import java.io.*;
import java.net.*;
class sevr implements Runnable{
public void run() {
ServerSocket sSkt = null;
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Server: is about to create socket");
sSkt = new ServerSocket(6666);
System.out.println("Server: socket created");
}
catch(IOException e){
System.out.println("Server: socket creation failure");
}
try{
System.out.println("Server: is listening");
skt = sSkt.accept();
System.out.println("Server: Connection Established");
}
catch(IOException e){
System.out.println("Server: listening failed");
}
try{
System.out.println("Server: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Server: stream done");
}
catch(IOException e){
System.out.println("Server: stream failed");
}
System.out.println("Server: reading the request");
try{
String line = null;
while((line =br.readLine()) != null){
System.out.println("Server: client said-> "+ line);
}
}
catch(IOException e){
System.out.println("Server: reading failed");
}
System.out.println("Server: reading fished");
System.out.println("Server: responding");
try{
bw.write("Hi! I am server!");
}
catch(IOException e){
System.out.println("Server: responding failed");
}
System.out.println("Server: responding finished");
System.out.println("Server: is finishing");
try {
br.close();
bw.close();
skt.close();
sSkt.close();
} catch (IOException e) {
System.out.println("Server: finishing failed");
}
System.out.println("Server: done");
}
}
class clnt implements Runnable{
public void run() {
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Client: about to create socket");
skt = new Socket(InetAddress.getLocalHost(),6666);
System.out.println("Client: socket created");
}
catch(IOException e){
System.out.println("Client: socket creation failure");
}
try{
System.out.println("Client: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Client: stream done");
}
catch(IOException e){
System.out.println("Client: stream failed");
}
System.out.println("Client: requesting");
try{
bw.write("Hi! I am Client!");
}
catch(IOException e){
System.out.println("Client: requesting failed");
}
System.out.println("Client: requesting finished");
System.out.println("Client: reading the respond");
try{
String line = null;
while((line =br.readLine()) != null){
System.out.println("Client: server said-> "+ line);
}
}
catch(IOException e){
System.out.println("Client: reading failed");
}
System.out.println("Client: reading fished");
System.out.println("Clientrver: is finishing");
try {
br.close();
bw.close();
skt.close();
} catch (IOException e) {
System.out.println("Client: finishing failed");
}
System.out.println("Client: done");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Main started");
Thread sThread = new Thread(new sevr());
Thread cThread = new Thread(new clnt());
sThread.start();
cThread.start();
try {
sThread.join();
cThread.join();
} catch (InterruptedException ex) {
System.out.println("joining failed");
}
System.out.println("Main done");
}
}
output:
Main started
Server: is about to create socket
Client: about to create socket
Client: socket created
Client: creating streams
Server: socket created
Server: is listening
Server: Connection Established
Server: creating streams
Server: stream done
Server: reading the request
Client: stream done
Client: requesting
Client: requesting finished
Client: reading the respond
and it waits here forever!
The program is using a BufferedWriter but this is not flushed (it will sit in the buffer until it is flushed, the buffer fills or closed) and there is no newline sent (the readLine will wait until you send a newline)
try
bw.write("I am the Client!!\n");
bw.flush();
Both threads hang on while((line =br.readLine()) != null)
now it works
package sockettest;
import java.io.*;
import java.net.*;
class sevr implements Runnable{
public void run() {
ServerSocket sSkt = null;
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Server: is about to create socket");
sSkt = new ServerSocket(6666);
System.out.println("Server: socket created");
}
catch(IOException e){
System.out.println("Server: socket creation failure");
}
try{
System.out.println("Server: is listening");
skt = sSkt.accept();
System.out.println("Server: Connection Established");
}
catch(IOException e){
System.out.println("Server: listening failed");
}
try{
System.out.println("Server: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Server: stream done");
}
catch(IOException e){
System.out.println("Server: stream failed");
}
System.out.println("Server: reading the request");
try{
String line = null;
line = br.readLine();
System.out.println("Server: client said-> "+ line);
}
catch(IOException e){
System.out.println("Server: reading failed");
}
System.out.println("Server: reading fished");
System.out.println("Server: responding");
try{
bw.write("Hi! I am server!\n");
bw.flush();
}
catch(IOException e){
System.out.println("Server: responding failed");
}
System.out.println("Server: responding finished");
System.out.println("Server: is finishing");
try {
br.close();
bw.close();
skt.close();
sSkt.close();
} catch (IOException e) {
System.out.println("Server: finishing failed");
}
System.out.println("Server: done");
}
}
class clnt implements Runnable{
public void run() {
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Client: about to create socket");
skt = new Socket(InetAddress.getLocalHost(),6666);
System.out.println("Client: socket created");
}
catch(IOException e){
System.out.println("Client: socket creation failure");
}
try{
System.out.println("Client: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Client: stream done");
}
catch(IOException e){
System.out.println("Client: stream failed");
}
System.out.println("Client: requesting");
try{
bw.write("Hi! I am Client!\n");
bw.flush();
}
catch(IOException e){
System.out.println("Client: requesting failed");
}
System.out.println("Client: requesting finished");
System.out.println("Client: reading the respond");
try{
String line = null;
line =br.readLine();
System.out.println("Client: server said-> "+ line);
}
catch(IOException e){
System.out.println("Client: reading failed");
}
System.out.println("Client: reading fished");
System.out.println("Client: is finishing");
try {
br.close();
bw.close();
skt.close();
} catch (IOException e) {
System.out.println("Client: finishing failed");
}
System.out.println("Client: done");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Main started");
Thread sThread = new Thread(new sevr());
Thread cThread = new Thread(new clnt());
sThread.start();
cThread.start();
try {
sThread.join();
cThread.join();
} catch (InterruptedException ex) {
System.out.println("joining failed");
}
System.out.println("Main done");
}
}
output:
Main started
Server: is about to create socket
Client: about to create socket
Client: socket created
Client: creating streams
Server: socket created
Server: is listening
Server: Connection Established
Server: creating streams
Client: stream done
Server: stream done
Server: reading the request
Client: requesting
Client: requesting finished
Client: reading the respond
Server: client said-> Hi! I am Client!
Server: reading fished
Server: responding
Server: responding finished
Server: is finishing
Client: server said-> Hi! I am server!
Client: reading fished
Client: is finishing
Client: done
Server: done
Main done

Categories