Studyon Minte9.com
Head First (Java)




Socket



To make a Socket connection, you need to know two things about the server: IP, and the port it's running on.
The port number must be between 1024-65535 (0-1023 are reserved for the well-known services). 

	%java
		
		// Testserver.java - SERVER

		package testexample;
		import java.io.*;
		import java.net.*;

		public class Testserver{
		    
		    public static void main(String[] args) {
			    
			try {
				// start the server application
				// listening for clients requests comming on port 4242
			    ServerSocket serverSocket = new ServerSocket(4242);
			    
			    System.out.println("Server started ...");
			    
				// server goes into a permanent loop, waiting for client requests
			    while(true) {
				
				    // after a request comes in, accept() returns a socket 
				    // for communicating with the client
				Socket socket = serverSocket.accept();

				    // make a writer
				PrintWriter writer = new PrintWriter(socket.getOutputStream());
				
				    // write message to the client
				writer.println("abc");
				writer.close();
				    //System.out.println("abc");
			    }
			} catch (IOException e) {
			    e.printStackTrace();
			}
		    }
		}

	%java

		// Testexample.java - CLIENT

		package testexample;
		import java.io.*;
		import java.net.*;

		public class Testexample{
		    
		    public static void main(String[] args) {
			
			System.out.println("Client started");
			
			try {
				// make a connection to the server
			    Socket socket = new Socket("127.0.0.1", 4242);
			    
				// ask the socket for an input stream
			    InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
			    
				// make a reader
			    BufferedReader reader = new BufferedReader(streamReader);
			    
				// read
			    String message = reader.readLine();
			    
				// print the message
			    System.out.println("The server message is: " + message);
			    
				// close reader
			    reader.close();
			    
			} catch(IOException e) {
			    e.printStackTrace();
			}
		    }
		    
		}