JAVA : Socket Basics – Loop

Server.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	private int port = 45234;
	ServerSocket serverSocket;
	Socket clientSocket;
	private PrintWriter out;
	private BufferedReader in;
	private String inputLine;
	private String outputLine;

	private void start() {
		try {
			serverSocket = new ServerSocket(port);
			clientSocket = serverSocket.accept();
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					clientSocket.getInputStream()));
			while ((inputLine = in.readLine()) != null) {
				if (inputLine.equals("bye")) {
					out.println("closing");
					break;
				}
				out.println("srv: " + inputLine);
			}
			System.out.println("server closing");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
				clientSocket.close();
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Server().start();
	}

}

Client.java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

	private int port = 45234;
	private Socket clientSocket;
	private PrintWriter out;
	private BufferedReader in;
	private BufferedReader stdIn;
	private String inputLine;
	private String outputLine;
	private void start() {

		try {
			clientSocket = new Socket("localhost", port);
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					clientSocket.getInputStream()));
			stdIn = new BufferedReader(new InputStreamReader(System.in));
			while ((inputLine = stdIn.readLine()) != null) {
				out.println(inputLine);
				outputLine = in.readLine();
				if(outputLine.equals("closing")) {
					break;
				}
				System.out.println(outputLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
				stdIn.close();
				clientSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Client().start();
	}

}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: