Mega Code Archive

 
Categories / Java / Network Protocol
 

Threaded Server with ServerSocket

import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; class ThreadedServer {   private final static int BUFSIZE = 512;   public static void main(String args[]) throws Exception {     int port = Integer.parseInt(args[0]);     ServerSocket ss = new ServerSocket(port);     while (true) {       Socket s = ss.accept();       ServerThread st = new ServerThread(s);       st.start();     }   } } class ServerThread extends Thread {   private double total = 0;   DataInputStream dis;   DataOutputStream dos;   public ServerThread(Socket s) throws Exception {     InputStream is = s.getInputStream();     dis = new DataInputStream(is);     OutputStream os = s.getOutputStream();     dos = new DataOutputStream(os);   }   public void run() {     try {       while (true) {         double value = dis.readDouble();         total += value;         dos.writeDouble(total);       }     } catch (Exception e) {     }   } }