Unit 3 Important Topics
Unit 3 Important Topics
2. Server Programming:
(a) Establish a Socket Connection: To write a server application two sockets are needed.
A ServerSocket which waits for the client requests (when a client makes a new
Socket())
A plain old Socket to use for communication with the client.
(b) Communication: getOutputStream() method is used to send the output through the
socket.
(c) Close the Connection : After finishing, it is important to close the connection by
closing the socket as well as input/output streams.
socket = server.accept();
System.out.println("Client accepted");
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
ServerSocket Class:
ServerSocket Class is used for providing system-independent implementa on of the
server-side of a client/server Socket Connec on.
The constructor for ServerSocket throws an excep on if it can’t listen on the specified
port (for example, the port is already being used).
implementation:
1. Server-Side
import java.io.*;
import java.net.*;
2. Client-Side
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args)
{
try {
Socket soc = new Socket("localhost", 6666);
DataOutputStream d = new DataOutputStream(
soc.getOutputStream());
d.writeUTF("Hello !");
d.flush();
d.close();
soc.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
getPort() Returns the port associated with the protocol specified by the URL
the Returns the query part of URL. A query is a part a er the ‘?’ in
getQuery() the URL. Whenever logic is used to display the result, there would
be a query field in the URL. It is similar to querying a database.