1. Try the "Client-Server" program below!
2. Type the source code below into a text editor such as Notepad + +, Edit + +, JCreators,
Eclipse or the other!
Server Aplication import java.io.*; import java.net.*; public Class Main { public static void main (String [] args) throws IOException {
ServerSocket server = null;
Socket client = null; byte[] receiveBuf = new byte[64]; int recvMsgSize; try { server = new ServerSocket (8881);
System.out.println(“Server started”); client = server.accept ();
System.out.println(“Client connected”);
} catch (IOException.e) {
System.out.println(e.getMessage());
System.exit(-1);
}
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
String data; data = “Message from Server”; out.write(data.getBytes()); java.util.Arrays.fill(receiveBuf, (byte)0); while (true) { recvMsgSize =in.read(receiveBuf); data = new string(receiveBuf); if (data.trim() .equals(“Exit”)) { out.write(data.getBytes()); break;
}
java.util.Arrays.fill(receiveBuf, (byte)0);
System.out.println(“Client: “ + data);
}
out.close(); in.close(); client.close(); server.close(); }
}
Client Aplication import java.io.*; import java.net.*; public class Main { public static void main (String[] args) throws IOException {
Socket client = null;
InputStream in = null;
OutputStream out = null; byte[] receiveMsg = new byte[64]; try { client = new Socket (“Connected”, 8881); in = client.getInputStream (); out = client.getOutputStream ();
} catch (UnknownHostException e) {
System.err.println(e.getMessage ());
System.exit (1);
} catch (IOException e) {
System.err.println(e.getMessage ());
System.exit (1);
}
String fromUser; in.read(receiveMsg); fromServer = new String (receiveMsg);
System.out.println(“Server: “ + fromServer); fromUser = “Message from Client”;
System.out.println(“Send to Server: “ + fromUser); out.write (fromUser.getBytes()); fromUser = “Data from