Client to Server Messaging
This example demonstrates the messaging from client to the server.
Client Side Implmentation
import java.net.*;
import java.io.*;
class Arjun {
public static void main(String[] args) throws IOException{
/* Let's use port 6666 for example. */
Socket s = new Socket("192.168.0.122",6666);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
// Writes the message in UTF Format.
dout.writeUTF("Hello, my Name is Arjun. Can I know information about my attendance status ?");
dout.flush();
dout.close();
s.close();
}
}
Server Side Implementation
import java.io.*;
import java.net.*;
class GCESServer {
public static void main(String[] args) throws IOException {
// Step 1: First, server should instatiate ServerSocket object.
ServerSocket ss = new ServerSocket(6666);
// Step 2 : Then, Server object envokes accept() method of ServerSocket class.
// This waits for client until client creates Socket object.
Socket s = ss.accept();
// This gets the message sent by the client.
DataInputStream dis = new DataInputStream(s.getInputStream());
// Typehinting the UTF message into string.
String message = (String) dis.readUTF();
System.out.println("Message from client : " + message);
ss.close();
}
}