Create Simple TCP / IP Client Application with Java

This some coding sample to creating socket connection in Java. This simple application will be sending message through TCP/IP connection and wait for response from server.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 *
 * @author Erwin
 */
public class SendMessage {

    public static void main(String[] args) {

        try {
            int port = 14000;

            // Create Socket address for configuring socket configuration
            SocketAddress sockaddr = new InetSocketAddress("127.0.0.1", port);

            // Create socket Object
            Socket sock = new Socket();

            // if timeout is reached and no response is received, it will throw socket exception
            int timeoutMs = 2000;   // in milliseconds

            // Initiate socket connection to server
            sock.connect(sockaddr, timeoutMs);
            try {
                
                // Create Buffered Writer object to write String or Byte to socket output stream
                BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
                String command = "Start Module";
                wr.write(command);
                System.out.println("Send String : "+command);
                
                // Flushing the writer
                wr.flush();

            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                String str;
                while ((str = rd.readLine()) != null) {
                    System.out.println(str);
                }
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            // Close socket connection after finish receiving a response
            sock.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Hope this will be helpfull. Regards, Erwin Lin

2 thoughts on “Create Simple TCP / IP Client Application with Java

Leave a comment