Java Sockets

Jussi Pohjolainen

TAMK University of Applied Sciences » ICT

What is a Socket?

Socket in Practice

Stream Socket in Java: Client and Server

// Client
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
	// Server address
	final String SERVERADDRESS = "localhost";
	// Server port
	final int SERVERPORT = 5091;

	// Socket between client and server
        Socket socket = null;
	// For sending message
        PrintWriter out   = null;
	// For receiving message
        BufferedReader in = null;

        try {
	    // Establish the connection to the server
            socket = new Socket(SERVERADDRESS, SERVERPORT);

	    // Get the socket's output stream and set autoflush
            // to true
            out = new PrintWriter(socket.getOutputStream(), true);

	    // Get the socket's input stream
            in = new BufferedReader(new InputStreamReader(
                                        socket.getInputStream()));

        } catch (UnknownHostException e) {
            System.err.println("Can't find host: " + SERVERADDRESS);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Failed to connect!");
            System.exit(1);
        }

	// Getting the user input
	Scanner scan = new Scanner(System.in);
	String userInput;
	
	// Repeat until user gives no longer input
	while ((userInput = scan.nextLine()) != null) {
	    // Push the user input to the server
	    out.println(userInput);
	    // Read and print the server's response
	    System.out.println("echo: " + in.readLine());
	}

	// Close all streams
	out.close();
	in.close();
	scan.close();
	socket.close();
    }
}

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

public class Server {
    public static void main(String[] args) throws IOException {
	// Server port
	final int SERVERPORT = 5091;
	
	// Server socket and the client socket
	ServerSocket serverSocket = null;
	Socket clientSocket       = null;

	// For input and output
	PrintWriter out           = null;
	BufferedReader in         = null;

	// Create the server socket
	serverSocket = new ServerSocket(SERVERPORT);
	// Wait for client
	clientSocket = serverSocket.accept();
	
	// Get the streams for input and output
	out = new PrintWriter(clientSocket.getOutputStream(), true);
	in  = new BufferedReader(new 
				 InputStreamReader(
						   clientSocket.getInputStream()));
	
	// Read client message and print it to the client
	String inputString;
	while ((inputString = in.readLine()) != null) {	
	    out.println(inputString);
	}

	// close streams and sockets
	out.close();
	in.close();
	clientSocket.close();
	serverSocket.close();
    }
}

Multiple clients?

Datagram sockets

Datagram sockets: Java