View RSS Feed

My Java Tips

Socket Programming (Client)

Rate this Entry
by , 11-09-2011 at 06:04 PM (1063 Views)
I will write a simple socket client, that will connect to the server, send data to the server and well get connection time stamp from the server.

In the example below, you will learn how to connect to a socket server and how to send and receive data.

First part is to declare client socket and input/output streams. Then we have to connect to the server using socket. While declaring socket object, we have to mention the host name and the port on which the server is listening. Once the connection is made, we will open streams and data exchange will take place.

Java Code:
                Socket smtpSocket = null;
		DataOutputStream os = null;
		DataInputStream is = null;

		try {
			smtpSocket = new Socket("nbooknm", 2222);
			os = new DataOutputStream(smtpSocket.getOutputStream());
			is = new DataInputStream(smtpSocket.getInputStream());
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host: hostname");
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for
                        the connection to: hostname");

		if (smtpSocket != null && os != null && is != null) {
			try {
				os.writeBytes("Hello Server");
				os.writeBytes("Please help me.");
				String responseLine;
				while ((responseLine = is.readLine()) != null) {
					System.out.println("Server: " + responseLine);
			} catch (UnknownHostException e) {
				System.err.println("Trying to connect to
                                unknown host: " + e);
			} catch (IOException e) {
				System.err.println("IOException:  " + e);

Server: Hi. You connected to the Server at: Mon Nov 26 14:57:02 CET 2007

What if you mention incorrect server hostname and port. You will get UnknownHostException if hostname is not found and you will get IOException if port is incorrect.

Submit "Socket Programming (Client)" to Facebook Submit "Socket Programming (Client)" to Digg Submit "Socket Programming (Client)" to Submit "Socket Programming (Client)" to StumbleUpon Submit "Socket Programming (Client)" to Google

Tags: None Add / Edit Tags
Network Programming