Java Networking

Protocals

TCP - Transmission Control Protocol

IP - Internet Protocal

UDP - User Datagram Packet

TCP/IP Socket Example

Socket <=> ServerSocket <=> Socket

Classes

ServerSocket
     - Socket accept()

Socket
     - InputStream getInputStream()
     - OutputStream getOutputStream()

InetAddress
     - InetAddress getLocalHost()
     - InetAddress getByName(String)

java.io.DataOutputStream
     - void writeUTF()
	 
java.io.DataInputStream
     - String readUTF()

Steps

Server

import java.net.*;
import java.io.*;

try {
	ServerSocket serverSocket = new ServerSocket(port);
	Socket socket = serverSocket.accept();
	
	// Server receive data from Client
	DataInputStream in = new DataInputStream(socket.getInputStream());
	System.out.println(in.readUTF());
	
	// Server send data to Client
	DataOutputStream out = new DataOutputStream(socket.getOutputStream());
	out.writeUTF("server -> client: some output data");
	
	server.close();
} catch (IOException e1 || SocketTimeoutException e2) {...}

Client

import java.net.*;
import java.io.*;

try {
	Socket socket = new Socket(serverName, port);
	
	// Client send data to Server
	DataOutputStream out = new DataOutputStream(socket.getOutputStream());
	out.writeUTF("client -> server: some output data");
	
	// Client receive data from Server
	DataInputStream in = new DataInputStream(socket.getInputStream());
	System.out.println(in.readUTF());
	
	client.close();
} catch(IOException e) {...}
Fork me on GitHub