JAVA : Socket Basics

Server

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

public class TestServer {
	private ServerSocket serverSocket;
	private Socket clientSocket;
	private PrintWriter out;
	private BufferedReader in;
	private String inputLine;
	private String outputLine;

	public void runServer() {
		try {
			serverSocket = new ServerSocket(55556);
			clientSocket = serverSocket.accept();
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					clientSocket.getInputStream()));
			out.println("Test Server...");
		} catch (Exception ex) {
			System.err.println("err in server");
		} finally {
			try {
				out.close();
				in.close();
				clientSocket.close();
				serverSocket.close();
			} catch (Exception e) {				
				System.err.println("err res closing in server");
			}
		}
	}

	public static void main(String[] args) {
		new TestServer().runServer();
	}

}

Client

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

public class TestClient {

	Socket socket;
	PrintWriter out;
	BufferedReader in;
	String fromServer;

	public void runClient() {
		try {
			socket = new Socket("myComp", 55556);
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			if ((fromServer = in.readLine()) != null) {
				System.out.println("from server" + fromServer);
			}
		} catch (Exception e) {
			System.err.println("err in client");
		} finally {
			try {
				out.close();
				in.close();
				socket.close();
			} catch (Exception e) {
				System.err.println("err res closing in client");
			}
		}
	}

	public static void main(String[] args) {
		new TestClient().runClient();
	}

}

Change myComp to your Computer name, to find the name of your computer run following code.

String computername = InetAddress.getLocalHost().getHostName();

Original Reference
All About Sockets – Oracle Tutorials

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: