-2
    Socket fromServer = new Socket("host", 443);

    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslsocket = (SSLSocket) factory.createSocket(fromServer, null, true);
    sslsocket.setUseClientMode(true);

i try it, but get "javax.net.ssl.SSLException: Received fatal alert: internal_error"

If i use SSLSocket directly it work (factory.createSocket("host", 443);)

add: i need add custom header BEFORE handshake, for implement custom protocol

add2: Code works! it my fail, i test on server with SNI

inter
  • 37
  • 1
  • 1
  • 4

1 Answers1

3

An SSLSocket transfers data within a TLS connection. A TLS connection need to be established before data can be transferred, i.e. the handshake must successfully complete. Thus it does not make sense to write to a SSLSocket before the handshake completed the same way it does not make sense to write to a TCP socket before the TCP connection got established.

add: i need add custom header BEFORE handshake, for implement custom protocol

After this information got added the question makes more sense. It looks like you want to first exchange unencrypted data and then upgrade to TLS later like done for example in SMTP+STARTTLS. In this case you need to first establish a normal TCP connection and then later upgrade it to TLS. See Is it possible to change plain socket to SSLSocket? for how to do the latter part.

Community
  • 1
  • 1
Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
  • i know it. i need add custom header BEFORE handshake, for implement custom protocol – inter Aug 19 '16 at 13:59
  • Well it does make sense if your protocol allows for safe **and** unsafe communication. If you want to handle both over the same port you can start naked and as soon as both parties have agreed on using SSL/TLS they can startTLS. An example would be SMTP ... – Fildor Aug 19 '16 at 14:23
  • Fildor, that's right – inter Aug 19 '16 at 14:41
  • @inter: I've updated the answer after you've updated the question. – Steffen Ullrich Aug 19 '16 at 16:34
  • thank, but pleas see my code, it like as code from your link. It not work actialy – inter Aug 19 '16 at 17:25
  • @inter: since it works with immediate handshake but not with plain text before the handshake my guess is that the server simply does not like the plain data before but expects a TLS handshake. You cannot simply send data the server cannot handle. – Steffen Ullrich Aug 19 '16 at 17:36
  • it work, but i test it on server with SNI. my fail. – inter Aug 19 '16 at 17:51