Data transmission between server and client is demonstrated using the two files given below. Client program have the code to send the data and server program have the code to receive the data. Data to be sent is added into Vector object and Vector is written into stream. Both server and client should be executed in same port for data transmission. Once the connection is established data is transmitted as a stream.
import java.net.*;
import java.io.*;
import java.util.*;
public class Server {
public static void main(String args[]) {
Vector vec = new Vector();
try {
ServerSocket ss = new ServerSocket(2222);
System.out.println("Server is waiting");
Socket sa = ss.accept();
System.out.println("Connected with client");
InputStream is = sa.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
vec = (Vector)ois.readObject();
String s1 = (String)vec.elementAt(0);
Integer s2 = (Integer)vec.elementAt(1);
System.out.println("Reading data "+ s1 + ": "+s2);
ois.close();
sa.close();
ss.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
public static void main(String args[]) {
String st = "Hai";
int n1 = 10221;
Vector v = new Vector();
v.addElement(st);
v.addElement(n1);
String hostname = ""; //slogix.in:
/* To execute in two different systems hostname of the system in which server program resides should be provided in hostname variable.
example:soft37
How to find hostname?
Go to command prompt and type: hostname
*/
try {
Socket s = new Socket(hostname,2222);
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(v);
System.out.println("Sending the data " + st + ": "+n1);
oos.flush();
oos.close();
s.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}