Ch 4
Ch 4
Networking in Java
Sockets,ports, URIs
Connecting to a server
• HTTPS – 443
• FTP – 21
• SMTP – 25
• DNS – 53
Example in Java:
When creating a socket, you specify the port number along with the IP
protocol://hostname:port/path?query#fragment
Protocol: Specifies the communication protocol ((e.g., http, ftp)
hostname: The domain name or IP address of the server (e.g.,
www.example.com)
port: (Optional) The port number on the server (default ports are used if
omitted, like port 80 for HTTP).
path: The specific location of the resource on the server (e.g., /page.html)
query: (Optional) A query string, usually used in HTTP for passing
parameters (e.g., ? Id=123)
fragment: (Optional) A reference to a specific section within the resource
(e.g., #section1)
Example
https://www.example.com:443/path/to/resource?query=value#section
Java example(using java.net.URL)
}
The client creates a socket to connect to the server at a specific IP address
and port. The step that used to create simple client using TCP stream are
1. Create socket object – obtain socket input and output stream
Socket client = new Socket(server, port_id)
2. Create I/O stream for communication between server
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
3. Perform I/O stream for communication between server
Receive data from server
os.writeBytes(“Hello \n”);
4. Close the socket
client.close();
for main function
try{
String meg = "";
Socket soc = new Socket("localhost", 1002);
DataInputStream input = new DataInputStream(soc.getInputStream());
DataOutputStream output = new DataOutputStream(soc.getOutputStream());
while(!meg.equals("exit")){
meg = input.readUTF();
text_area.setText(text_input.getText() + "\n Server says: " + meg);
}
}
catch (Exception e){
}
For send button
try{
String msg = "";
msg = text_input.getText();
output.writeUTF(msg);
}
catch(Exception e){
}
Establishing a simple server using UPD