title: Java Socket Programming: How to send <STX>string-data<ETX> over TCP connection to the server?
body: <p>I have to establish a TCP connection to a server, which requires that I send the credential to logon in the format:</p>
  
  <p><strong>&lt; STX >username=fred&amp;password=123456&lt; ETX ></strong></p>
  
  <p>Let's say host: qstage.thetcphost.com and port:8999</p>
  
  <p>I am new to socket programming and using the same to implement this. I have used java.net.Socket at the client side but I dont know how do I send the above string for authentication to the TCP Server in Java.</p>
  
  <p>I am able to connect to the server but how do I pass the credential string in the &lt; STX >...&lt; ETX > format after (or during): 
  Socket socket = new Socket("mshxml.morningstar.com", 8999);</p>
  
  <p>I mean what is the piece of code that I have to write (after above line) to send this data (username &amp; password wrapped in STX and ETX) in order to authenticate myself to the TCP server?</p>
  
  <p>I have searched this site for this info but could not find any. Help would be greatly appreciated.</p>
  
  <p>Code goes like:</p>
  
  <pre><code>Socket socket = new Socket("msd4xml.abcd.com", 8999, InetAddress.getLocalHost(), 8999);
      System.out.println(socket.isConnected());
      InputStream inStream = socket.getInputStream();
      OutputStream outStream = socket.getOutputStream();
      DataOutputStream dout = new DataOutputStream(outStream);
      int stx = 0x02;
      int etx = 0x03;
  
      dout.writeByte(stx);
      dout.writeBytes("username=fred&amp;password=12345");   // this line gives error, infact every 2nd writeByte(s) gives error.
      dout.writeByte(etx);
  </code></pre>
  
  <p>It's giving:</p>
  
  <pre><code>Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error
  at java.net.SocketOutputStream.socketWrite0(Native Method)
  at java.net.SocketOutputStream.socketWrite(Unknown Source)
  at java.net.SocketOutputStream.write(Unknown Source)
  at java.io.DataOutputStream.writeBytes(Unknown Source)
  at com.voya.socketprog.Client.main(Client.java:44)
  </code></pre>