a simple client/server source in java
in building the client / server application we will make two initial source, the server source and the client source for connections to the server.
The following is a simple example of the connection client / server using TCP.
code for the server :
/**
* Tserver.java
* Example server program using TCP.
*/
import javax.swing.*;
public class Tserver {
final static int serverPort = 3456; // port server location
public static void main(String args[]) {
java.net.ServerSocket sock = null; // server socket location
java.net.Socket clientSocket = null; // creating socket
java.io.PrintWriter pw = null; // output soket
java.io.BufferedReader br = null; // input soket
try {
sock = new java.net.ServerSocket(serverPort); // create socket and bind to port
System.out.println("waiting connection from client..");
clientSocket = sock.accept(); // waiting connection from client
System.out.println("connection successfull");
pw = new java.io.PrintWriter
(clientSocket.getOutputStream(),true);
br = new java.io.BufferedReader(
new java.io.InputStreamReader(clientSocket.getInputStream()));
Integer r = Integer.parseInt(br.readLine()); // read message from client
Double hsl = 3.14 * r * r ;
//System.out.println("pesan dari client.. >" + hsl);
JOptionPane.showMessageDialog(null,answer "+hsl); // send response to client
pw.close(); // closing
br.close();
clientSocket.close();
sock.close();
} catch (Throwable e) {
System.out.println("Error " + e.getMessage());
e.printStackTrace();
}
}
}
code for the client :
Java Programming for a Beginner, 5-disk DVD Complete Training Suite. Edition 2009
0 Response to "a simple client/server source in java"
Post a Comment