Programmazione
Asp
Asp.NET
Java
Javascript
Php
Oracle

Svaghi
Ascolta Radio
Faccine
Libri
Links

Varie
Cerca nel sito...
Segnalazioni
Scrivimi


JAVA server socket

SocketServer un sempicissimo esempio di server framework; apre un listener su una data porta e poi attende le connessioni.
Per ogni chiamata entrante crea una processo che valuta la richiesta e muore immediatamente.
Questo ovviamente non il modo migliore per implementare un server multi-threaded a causa dell'eccessivo utilizzo delle risorse di sistema che vengono occupate, ma pur sempre un utile e valido esempio.

import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.text.SimpleDateFormat;

public class SocketServer implements Runnable {
   private int port = 12345;
   public SocketServer() {
   
   }

   public SocketServer( int port ) {
      this.port = port;
   }

   public void run() {
      try {
         ServerSocket serverSocket = new ServerSocket( port );
         System.out.println( "listening on port " + port );
         while( true ) {
            Socket socket = serverSocket.accept();
            Thread thread = new Thread( new ServerThread( socket ) );
            thread.setDaemon( true );
            thread.start();
         }
      }

      catch( Exception e ) {
         e.printStackTrace();
      }
   }

   public static void main( String[] args ) {
      try {
         Thread socketServer = new Thread( new SocketServer() );
         socketServer.setDaemon( true );
         socketServer.start();
         BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
         String s;
         System.out.println( "Type ! to quit..." );
         while( !(s = br.readLine()).trim().equals("!") )
            System.out.println( "Type ! to quit..." );
         socketServer.join(1);
      }catch( Exception e ) {
         e.printStackTrace();
      }
   }

}



class ServerThread implements Runnable {
   private static int count = 0;
   private int id = ++count;
   private Socket socket = null;
   private byte[] buffer;
   private int msgOffset = 0;
   private final byte[] HEADER = "".getBytes();
   private final int BUFFER_LENGTH = 10240;
   
   public ServerThread( Socket socket ) {
      this.socket = socket;

   }

   public void run() {
      try {
         System.out.println( "Thread " + id + " is running...");
         buffer = new byte[BUFFER_LENGTH];
         msgOffset = 0;
         for( msgOffset = 0; msgOffset < HEADER.length; msgOffset++ )
            buffer[msgOffset] = HEADER[msgOffset];
   
         try {
               int read = socket.getInputStream().read( buffer, msgOffset, BUFFER_LENGTH - msgOffset );
               String Input = new String(buffer);
               String Output = new String("");
		// do something useful here
		// now, return the input string
		// with the prefix 'you said'

		Output = "You Said " + Input;
        	byte[] OutMsg = Output.getBytes();
                socket.getOutputStream().write( OutMsg );
                socket.getOutputStream().flush();
                socket.getOutputStream().close();
         }catch( SocketException se ) {
                  se.printStackTrace();
         }

         socket.close();
         count = count -1;
         System.out.println( "Thread " + id + " is quitting...");
      }catch( Exception e ) {
         e.printStackTrace();
      }
   }