Through the classes in java.net, Java programs can
use TCP or UDP to communicate over the Internet. The URL, URLConnection, Socket,
and ServerSocket classes all use TCP to communicate over the network. The
DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with
UDP.
This hands-on lab takes you through the basics of
using Java networking.
/* SERVER – may enhance to work for
multiple clients */ import java.net.*; import java.io.*; public class NetworkingServer { public static void main(String [] args) { ServerSocket server = null; Socket client; // Default port number we are going to use int portnumber = 1234; if (args.length >= 1){ portnumber = Integer.parseInt(args[0]); } // Create Server side socket try { server = new ServerSocket(portnumber); } catch (IOException ie) { System.out.println("Cannot open socket." + ie); System.exit(1); } System.out.println("ServerSocket is created " + server); // Wait for the data from the client and reply while(true) { try { // Listens for a connection to be made to // this socket and accepts it. The method blocks until // a connection is made System.out.println("Waiting for connect request..."); client = server.accept(); System.out.println("Connect request is accepted..."); String clientHost = client.getInetAddress().getHostAddress(); int clientPort = client.getPort(); System.out.println("Client host = " + clientHost + " Client port = " + clientPort); // Read data from the client InputStream clientIn = client.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(clientIn)); String msgFromClient = br.readLine(); System.out.println("Message received from client = " + msgFromClient); // Send response to the client if (msgFromClient != null && !msgFromClient.equalsIgnoreCase("bye")) { OutputStream clientOut = client.getOutputStream(); PrintWriter pw = new PrintWriter(clientOut, true); String ansMsg = "Hello, " + msgFromClient; pw.println(ansMsg); } // Close sockets if (msgFromClient != null && msgFromClient.equalsIgnoreCase("bye")) { server.close(); client.close(); break; } } catch (IOException ie) { } } } } |
ServerSocket is created
ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=1234] Waiting for connect request... |
/* CLIENT */ import java.io.*; import java.net.*; public class NetworkingClient { public static void main(String args[]) { Socket client = null; // Default port number we are going to use int portnumber = 1234; if (args.length >= 1){ portnumber = Integer.parseInt(args[0]); } for (int i=0; i <10; i++) { try { String msg = ""; // Create a client socket client = new Socket(InetAddress.getLocalHost(), portnumber); System.out.println("Client socket is created " + client); // Create an output stream of the client socket OutputStream clientOut = client.getOutputStream(); PrintWriter pw = new PrintWriter(clientOut, true); // Create an input stream of the client socket InputStream clientIn = client.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(clientIn)); // Create BufferedReader for a standard input BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter your name. Type Bye to exit. "); // Read data from standard input device and write it // to the output stream of the client socket. msg = stdIn.readLine().trim(); pw.println(msg); // Read data from the input stream of the client socket. System.out.println("Message returned from the server = " + br.readLine()); pw.close(); br.close(); client.close(); // Stop the operation if (msg.equalsIgnoreCase("Bye")) { break; } } catch (IOException ie) { System.out.println("I/O error " + ie); } } } } |
Client socket is created
Socket[addr=Passion2/192.168.2.4,port=1234,localport=1775] Enter your name. Type Bye to exit. |
I/O error java.net.ConnectException:
Connection refused: connect I/O error java.net.ConnectException: Connection refused: connect I/O error java.net.ConnectException: Connection refused: connect I/O error java.net.ConnectException: Connection refused: connect |
ServerSocket is created
ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=1234] Waiting for connect request... Connect request is accepted... Client host = 192.168.2.4 Client port = 1775 Message received from client = Sang Shin Waiting for connect request... Connect request is accepted... Client host = 192.168.2.4 Client port = 1777 |
import java.net.*; public class MulticastChatServer { public static void main(String args[]) throws Exception { // Default port number we are going to use int portnumber = 5000; if (args.length >= 1) { portnumber = Integer.parseInt(args[0]); } // Create a MulticastSocket MulticastSocket serverMulticastSocket = new MulticastSocket(portnumber); System.out.println("MulticastSocket is created at port " + portnumber); // Determine the IP address of a host, given the host name InetAddress group = InetAddress.getByName("225.4.5.6"); // getByName- returns IP address of given host serverMulticastSocket.joinGroup(group); System.out.println("joinGroup method is called..."); boolean infinite = true; // Continually receives data and prints them while (infinite) { byte buf[] = new byte[1024]; DatagramPacket data = new DatagramPacket(buf, buf.length); serverMulticastSocket.receive(data); String msg = new String(data.getData()).trim(); System.out.println("Message received from client = " + msg); } serverMulticastSocket.close(); } } |
MulticastSocket is created at port
5000 joinGroup method is called... |
import java.net.*; import java.io.*; public class MulticastChatClient { public static void main(String args[]) throws Exception { // Default port number we are going to use int portnumber = 5000; if (args.length >= 1) { portnumber = Integer.parseInt(args[0]); } // Create a MulticastSocket MulticastSocket chatMulticastSocket = new MulticastSocket(portnumber); // Determine the IP address of a host, given the host name InetAddress group = InetAddress.getByName("225.4.5.6"); // Joins a multicast group chatMulticastSocket.joinGroup(group); // Prompt a user to enter a message String msg = ""; System.out.println("Type a message for the server:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); msg = br.readLine(); // Send the message to Multicast address DatagramPacket data = new DatagramPacket(msg.getBytes(), 0, msg.length(), group, portnumber); chatMulticastSocket.send(data); // Close the socket chatMulticastSocket.close(); } } |
Type a message for the
server: |
MulticastSocket is created at port
5000 joinGroup method is called... Message received from client = Hello Server |