Skip to main content

A Simple Java TCP Client

As followed my post about simple java TCP server and I promised to post about simple java TCP client, so here it is. If you haven't read my simple java TCP server already, then why don't you give it a go. There you'll find how to compile java code that I will not be covering in this post. So go ahead to this post and get back here as soon as you know how to compile java code. If you already know how to do it, then it's okay to continue to read this post.
import java.io.*;
import java.net.*;
import java.util.Scanner;

class Client{
    private static Client client;
    private static int socketNumber = 1234;
    private static Socket clientSocket;

    public Client(){
        try{
            clientSocket = new Socket("localhost", getSocket());
        }catch(Exception e){
            System.out.println("Error."+e.getMessage());
        }
    }

    private int getSocket(){
        Scanner in = new Scanner(System.in);
        System.out.print("Input socket server: ");
        socketNumber = in.nextInt();
        System.out.println("Socket server "+socketNumber+", Ready to send message");
        return socketNumber;
    }

    public static void main(String argv[]) throws Exception{
        client = new Client();
        String sentence;  
        String modifiedSentence;   
        BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));   
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());   
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));   
        sentence = inFromUser.readLine();   
        outToServer.writeBytes(sentence + '\n');   
        modifiedSentence = inFromServer.readLine();   
        System.out.println("FROM SERVER: " + modifiedSentence);   
        clientSocket.close();
    }
} 
Compile and run the code.
To test this out, we need to run the server as well so go ahead open another terminal and run the server. Put the socket port you want your server will be using and press ENTER Then in your client, put the server port that you just typed in and press ENTER. Now you'll see "Ready to send message" message, it indicates that both client and server are now connected.
Just type something from client then you'll see your message will be appeared in the server side.

To test our server from a different computer, we need know our PC ip address. To find out our IP address, simply type in terminal ipconfig for windows or ifconfig for ubuntu and our IP address is shown next to inet label.
After we know our PC's IP,  open terminal from another computer which runs ubuntu and type in telnet <our ip address> <server port> and we're ready to send message to server.

#source: https://systembash.com/a-simple-java-tcp-server-and-tcp-client/

Comments

Popular posts from this blog

Korps Dai Mahasiswa (KDM) Salman ITB

Dai Corps Students, or shortened to KDM Salman ITB , is a recitation of activities held at Salman Mosque and intended for ITB students and also public. Located in the South Corridor Salman Mosque, KDM Salman ITB is trying to bring teaching activities with the concept of traditional pesantren (traditional boarding school). With meetings every day after dhuhur, the students who take part in this Salman KDM get the study material by using the yellow books (kitab kuning) as a handle, as in the traditional pesantren. Teachers who bring the study also vary depending on the items of its study, they are ustadzs from Salman mosque itself. KDM Salman ITB appears to address concerns some students, as well as some ustadzs in mosques Salman, who feel that it is necessary to foster student containers in religious matters. It is motivated by the proliferation of such activities 'mentoring' on campus. But the mentor who brought the material (ie students) were deemed less or even not ...

Ramadhan 1435H & Silaturahmi keluarga

Baju baru alhamdulillah, tuk dipakai di hari raya, Tak punya pun tak apa-apa, masih ada baju yang lama. Sepatu baru alhamdulillah, tuk dipakai di hari raya, Tak punya pun tak apa-apa, masih ada sepatu yang lama. Kue baru alhamdulillah, tuk dimakan di hari raya, Tak punya pun tak apa-apa, masih ada kue yang lama. /wahaha Alhamdulillah, tidak terasa ramadhan telah berlalu. Rasa syukur ku kepada Allah SWT. karena telah diberi kesempatan untuk bisa bertemu ramadhan tahun ini sampai selesai. Meskipun Ramadhan udah selesai, semoga hati dan jiwa tetap fitri dan selalu terjaga. Ramadhan kali ini sangat menyenangkan meskipun setengahnya aku jalanin tanpa keluarga, tanpa sanak saudara yang menemani jerih payah puasa. /sweat Tapi ngga papa, yang penting inti dari ibadah bulan ramadhan tetep didapat. #intinya apa ya? Seperti ramadhan-ramadhan sebelumnya, setiap satu minggu sebelum lebaran ibu (dan aku) pasti bikin kue-kue penghias meja. Kali ini pun sama. Aksi bikin kue pun terjadi...

Lakukan Apapun yang Menjadi Renjana-mu Meskipun Hidupmu Semenjana

Judul di atas mungkin sedikit sulit diartikan atau bahkan membingungkan bagi kita. Mungkin ada juga yang mengira kalau aku menyisipkan kata-kata asing atau apa. Padahal sebenarnya, semua deretan kata dalam judul diatas murni bahasa kita tercinta, Bahasa Indonesia. Ya, semuanya kata asli Indonesia. Hanya saja kita tidak terbiasa menggunakannya yang membuat kita merasa asing. Padahal jika aku ganti dengan kata asing, kalimat itu justru tidak asing. Ini nih: "Lakukan Apapun yang Menjadi Passion -Mu Meskipun Hidupmu Biasa-biasa Saja ". Sekarang jauh lebih mudah dimengerti kan? Terlepas apakah kalimat itu punya makna atau tidak, akan tetapi, kita lebih mudah mencerna setiap kata dalam kalimat itu. Hal ini memang miris mengingat kita lebih kenal dan lebih dekat dengan bahasa asing dari pada bahasa asli sendiri yang membuat kita merasa asing dengan bahasa sendiri dan bahasa asing malah tidak terasa asing karena sering kita gunakan. #mbulet-mbulet kalimatnya Sis: "Bro, ...