JAVA

JAVA - NETWORKING

mossybeach 2024. 7. 15. 17:48

Today we learnt about the wonders of networking in Java! It was so exciting to find out how we actually receive and send information between users and servers! I adore learning about the ins and outs of CS!


Networking?

think of it as a web that connect one computer to another

It is where two or more computers are connected via a cable (could be a literal or not) to form a network.

 

The network is comprised of two parts:

Server: the side which provides the information

Client: who uses said information/service 

 

there is also what is called as P2P (Peer to Peer): where clients also work as a server (sharing information): a good example is Limewire!

 


OSI: Open Systems Interconnection model

source

The Open Systems Interconnection (OSI) model is a conceptual framework that divides network communications functions into seven layers. 

 

The layers of the Open Systems Interconnection (OSI) model encapsulate every type of network communication across both software and hardware components. The model was designed to allow two standalone systems to communicate via standardised interfaces or protocols based on the current layer of operation.

 

 

physical layer (level 1)

  • refers to the physical communication medium and technologies to transmit data across said medium.
  • A transfer of digital and electronic signals through physical channels: fibre-optic cables, copper cabling, air.
  • Also related to channels such as Bluetooth, NFC and data transmission speeds.

 

Data link layer (level 2)

  • refers to tech used to connect two machines across a network where physical layer already exists: ethernet
  • Manages data frames where digital signals are created into data packets: pieces of something that combines for a bigger picture (think jigsaw puzzle)
  • Flow control and error control of data are often key focuses
  • spilt into two sub-layers: Media Access Control & Logical Link Control

 

Network Layer

  • routing, forwarding. addressing across dispersed network or multiple connections of nodes/machines
  • may also manage flow control
  • Internet Protocol v4(IPv4) and IPv6 are used as main network layer protocols

 

Transport layer

  • Primary focus:ensure data packets arrive in the right order without losses or errors or can be seamlessly recovered if needed
  • Flow control and error control is a focus at the layer
  • Commonly used protocols: 
    -Transmission Control Protocol: near lossless connection-based protocol, used when all data must be intact
    -User Datagram Protocol: a lossy connectioness protocol, used when retaining all packet is less critical

 

Session Layer

  • Responsible for network coordination between two seperate applications in a session.
    > a session manages the beginning and ending of a 1:1 application connection and synchronization conflicts.
  • Network File System and Server Message Block are commonly used protocols at the layer

 

Presentation Layer

  • concerned with syntax of data itself for applications to send and consume
  • HTML, JSON and CSV are all modelling lang to describe the structure of data at the presentation layer

 

Application layer

 

  • concerned with specific type of application itself and its standardized communication methods
    > browsers can comminucate using HyperText Transfer Protocol Secure (HTTPS) and HTTP
    > email clients can  communicate using POP3 and SMTP

IP addresses

All computers  (including phone and laptop) use IP addresses to find and communicate to each other.

 

DNS or Domain Name System is the handy tool that converts the IP addresses which are a long string of numbers into something humans can read, like /www.example.com/

 

In the past we used the IPv4 format for IP addresses which was 32 bit for when there weren't a lot of computers around. 

However due to advancement we used up all the addresses so now we use a 128 bit IPv6.


WIFI uses a MAC address... but what is that?

A MAC (Media Access Control) address is  unique 48-bit format numbers for the physical address of a network device.

> 12 digit hexadecimal number


Computer Ports :  a virtual point where network connections start and end.

Each port is associated with a specific process or service.

Web service 80,8080,443
FTP 21
DB 3306,1502
mail 25

 


UDP & TCP

TCP

  • works like a phone: connects with the other user before transferring data
  • Checks if previous data is sent before loading a new one
  • If not sent, it tries again
  • used for important documents and data

UDP

  • works like a message: transfers data without connection
  • doesn't check if it has been sent successfully
  • quick transfer rate, however there could be data bleeding
  • used for non-important data: video streaming

Socket & Server Socket

Socket: handles communication between processes: has inputStream and OutputStream

> uses the two streams to communicate (input and output) between processes

 

Server Socket: connects to the port and waits for an external connection request

>once request is received creates a socket and transfers info between the sockets.

 

There is one socket per port!!

 

The process of communication

1. A server uses a server socket to wait for the client on the designated port of the server computer

2. The client creates a socket using the server's ip address and port info and sends a connection request to the server

3. The server socket creates a new socket and communicates with the client once the client's request is received

4. The client and server sockets communicates 1:1


The above but in code!!

server side:

public class Socket01 {

 

public static String getTime(){

SimpleDateFormat sdf = new SimpleDateFormat("[hh:mm:ss]");

return sdf.format(new Date());

}

 

public static void main(String[] args) {

//server socket

ServerSocket serverSocket = null;

try {

serverSocket = new ServerSocket(3001); > creates a serversocket connected to port 3000

port number can be anything except for the select ones like 8080

System.out.println(getTime() + " 접속되었습니다");

 

while (true) {

System.out.println("접속 대기중");

Socket socket = serverSocket.accept(); > method listens for connection to be made then accepts, passive till then

System.out.println(getTime() + ":" + socket.getInetAddress()); > gets address of computer(client) that requested info

 

Output stream

OutputStream os = socket.getOutputStream();

DataOutputStream dos = new DataOutputStream(os);

 

Sends over remote socket

dos.writeUTF(getTime() + "서버가 보낸 메세지 입니다");

System.out.println(getTime() + "데이터를 전송했습니다");

 

dos.close();

socket.close();

}

} catch (IOException e) {

e.printStackTrace();

}finally {

try {

serverSocket.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

 

Client side:

public class ClientSocket {

public static void main(String[] args) {

 

String ip = "localhost"; > localhost means my computer = local host 172.30.1.87

System.out.println("서버에 접속 중입니다");

 

try {

Socket socket = new Socket(ip, 3001);

InputStream is = socket.getInputStream();

DataInputStream dis = new DataInputStream(is);

 

System.out.println("서버에서 온 메시지 : " + dis.readUTF());

System.out.println("연결 종료");

 

dis.close();

socket.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}