Using Sockects For Both TCPIP & UDP
Using Sockects For Both TCPIP & UDP
In this example, the server will await ('listen for') a connection from a
client on port 1234.
output.println("Awaiting data...");
String input = input.nextLine();
• The following example program is used to illustrate the use of these steps.
• We create a Socket object, supplying its constructor with the following two
arguments:
• the server's IP address (of type InetAddress);
• the appropriate port number for the service.
• (The port number for server and client programs must be the same, of
course!)
• For simplicity's sake, we shall place client and server on the same host, which
will allow us to retrieve the IP address by calling static method getLocalHost
of class. For example:
• These are set up in exactly the same way as the server streams were set up
(by calling methods getInputStream and getOutputStream of the Socket
object that was created in step 2).
• The Scanner object at the client end will receive messages sent by the
PrintWriter object at the server end,
• while the PrintWriter object at the client end will send messages that are
received by the Scanner object at the server end (using methods nextLine
and println respectively).
• This is exactly the same as for the server process (using method close of
class Socket).
“DatagramPacket objects are created and sent at both ends, rather than
simple strings. “
datagramSocket.receive(inPacket);
• For example:
• Steps 4-6 below are exactly the same as steps 2-4 of the server procedure.
• For example:
datagramSocket.close();