title: TCP server and TCP client in java
body: <p>I am trying to implement TCP server and client in my spring boot app.
  Initially my controller receives response from another application, on receiving this response, my service class calls another method which sets up a tcp connection. After the tcp connection has been established I call a method which sets up a tcp client. The TCP server keeps on listening for message from the machine on which the connection has been established and various actions are performed on the basis of the message name. Every time I execute the code, I get the following error:</p>
  
  <pre><code>java.net.BindException: Address already in use: JVM_Bind
      at java.net.DualStackPlainSocketImpl.bind0(Native Method)
      at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
      at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
      at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
      at java.net.ServerSocket.bind(ServerSocket.java:375)
      at java.net.ServerSocket.&lt;init&gt;(ServerSocket.java:237)
      at java.net.ServerSocket.&lt;init&gt;(ServerSocket.java:128)
      at com.epbRestServer.tcp.TCPServer.setupTCPConnection(TCPServer.java:24)
      at com.epbRestServer.service.impl.EPBRestServerServiceImpl.handleStartEPC(EPBRestServerServiceImpl.java:28)
      at com.epbRestServer.controller.EPBRestServerController.startEPC(EPBRestServerController.java:27)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
      at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
      at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
      at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
      at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
      at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      at java.lang.Thread.run(Thread.java:745)
  </code></pre>
  
  <p>The code which calls tcp client and tcp server methods:</p>
  
  <pre><code>public ResponseBean handleStartEPC(RequestBean request) {
      // Code for establishing tcp connection
      ResponseBean response = new ResponseBean();
  
      if (request != null) {
          TCPServer tcpServer = new TCPServer();
          response = tcpServer.setupTCPConnection(request);
          if (response.getTcpConnect()) {
              TCPClient tcpClient = new TCPClient();
              TCPRequestBean tcpBean = new TCPRequestBean();
              String str = new String();
              str = str.concat("IP:").concat(request.getIpAddress()).concat(",NodeName:").concat(request.getVduName())
                      .concat(",Interface:").concat(request.getInterfaceName());
              int length = str.length();
              str = "Length:" + length +"," + str;
              tcpBean.setIpAddress(request.getIpAddress());
              tcpBean.setInputData(str);
              response = tcpClient.setupTCPClient(tcpBean);
          }
  
          else {
              response.setStatus("FAILURE");
          }
  
      }
  
      else {
          response.setStatus("FAILURE");
      }
  
      return response;
  }
  </code></pre>
  
  <p>The code for tcp client and tcp server</p>
  
  <pre><code>public class TCPServer {
  
      @Autowired
      EPBRestServerService epbRestServerService;
  
      public ResponseBean setupTCPConnection(RequestBean request) {
  
          ResponseBean response = new ResponseBean();
          try {
              ServerSocket server = new ServerSocket(8000);
              Socket s = server.accept();// establishes connection
              DataInputStream dis = new DataInputStream(s.getInputStream());
              String str = (String) dis.readUTF();
              VNFNotificationRequestBean vnfRequestBean = new VNFNotificationRequestBean();
              System.out.println("message:" + str);
              switch (str.toLowerCase()) {
              case "restAPIResponse":
                  response.setTcpConnect(true);
                  response.setStatus("SUCCESS");
                  break;
              case "startsuccess":
                  vnfRequestBean.setEvent("StartSuccess");
                  vnfRequestBean.setSystemId(request.getSystemId());
                  vnfRequestBean.setContent("ContentType - application/json");
                  response = epbRestServerService.triggerEvent(request, vnfRequestBean);
                  break;
              case "initsuccess":
                  vnfRequestBean.setEvent("InitSuccess");
                  vnfRequestBean.setSystemId(request.getSystemId());
                  vnfRequestBean.setContent("ContentType - application/json");
                  response = epbRestServerService.triggerEvent(request, vnfRequestBean);
                  break;
              case "configuresuccess":
                  vnfRequestBean.setEvent("ConfigureSuccess");
                  vnfRequestBean.setSystemId(request.getSystemId());
                  vnfRequestBean.setContent("ContentType - application/json");
                  response = epbRestServerService.triggerEvent(request, vnfRequestBean);
                  break;
              default:
                  response.setStatus("FAILURE");
                  break;
              }
              server.close();
          } catch (IOException e) {
              response.setTcpConnect(false);
              e.printStackTrace();
          }
          return response;
  
      }
  
      public class TCPClient {
  
          public ResponseBean setupTCPClient(TCPRequestBean request) {
  
              ResponseBean response = new ResponseBean();
              try {
                  Socket s = new Socket(request.getIpAddress(), 8000);
                  DataOutputStream dout = new DataOutputStream(s.getOutputStream());
                  dout.writeUTF(request.getInputData());
                  dout.flush();
                  dout.close();
                  s.close();
                  response.setStatus("SUCCESS");
              } catch (IOException e) {
                  System.out.println(e);
                  response.setStatus("FAILURE");
              }
              return response;
          }
  
      }
  </code></pre>