Client Socket In Java Example

Chapter: Networking Last Updated: 30-04-2016 19:04:04 UTC

Program:

            /* ............... START ............... */
                
import java.net.*;
import java.io.*;

public class JavaClientSocketExample {

	public static void main(String[] args) {
		
		String serverName = args[0];
		int port = Integer.parseInt(args[1]);
		try {
			System.out.println("Connecting to " + serverName + " on port " + port);
			Socket client = new Socket(serverName, port);
			System.out.println("Just connected to " + client.getRemoteSocketAddress());
			OutputStream outToServer = client.getOutputStream();
			DataOutputStream out = new DataOutputStream(outToServer);
			out.writeUTF("Hello from " + client.getLocalSocketAddress());
			InputStream inFromServer = client.getInputStream();
			DataInputStream in = new DataInputStream(inFromServer);
			System.out.println("Server says " + in.readUTF());
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

                /* ............... END ............... */
        

Output

java JavaClientSocketExample localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!

Tags

Client Socket, Java, Networking

Similar Programs Chapter Last Updated
Java URL Parts Example Networking 28-10-2016
Java Program To Create Socket At Specific Port Networking 28-10-2016
Java Find Proxy Settings Networking 10-09-2016
Java Download Webpage Example Networking 09-09-2016
Java URL Connection Date Networking 09-09-2016
Java Socket To Single Client Networking 09-09-2016
Java Server File Size Example Networking 09-09-2016
Java Multithreaded Server Example Networking 09-09-2016
Java Server File Modification Time Networking 09-09-2016
Java Connect To Server Example Networking 09-09-2016
Http Response Header In Java Example Networking 21-06-2016
Server Socket In Java Example Networking 30-04-2016
Socket Programming In Java Networking 30-04-2016
IP Address And HostName Of Local Computer In Java Networking 30-04-2016
HostName And IP Address In Java Networking 30-04-2016
Read And Download Webpage In Java Example Networking 29-04-2016
Date Of URL Connection In Java Example Networking 29-04-2016
Who Is Lookup In Java Example Networking 21-07-2016
System Proxy In Java Example Networking 21-09-2018
Port Scanner In Java Example Networking 21-07-2016
Ping IP Address In Java Example Networking 21-09-2018
MAC Address In Java Example Networking 22-09-2018
Get IP Address In Java Example Networking 07-04-2016
URL Properties In Java Example Networking 09-09-2016
Default URL Object In Java Example Networking 18-07-2016

1