How To Send Message To Server Using Socket In Java

Here is simple class to send message to server. You can change the IP and port server based on your requirement. I use 127.0.0.1 and port 8080 for example. The message that you want to send will be from input dialog.

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import javax.swing.JOptionPane;

public class SimpleClient {
    public static void main(String[]args){
        String msg = JOptionPane.showInputDialog("Please input message "); //get msg
        if(msg != null && !msg.isEmpty()){ //if not empty
            try {
                Socket socket = new Socket("127.0.0.1", 8080); //create socket
                OutputStream outStream = socket.getOutputStream(); //get the outputstream of socket
                outStream.write(msg.getBytes()); //send msg
                outStream.flush();
                outStream.close();
                socket.close();
            } catch (IOException e) {
            }
        }
    }
}

Hope this simple sample can help.. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s