1 24 package org.objectweb.jalisto.test.core.remote.other; 25 26 import org.objectweb.jalisto.se.exception.JalistoException; 27 28 import java.io.IOException ; 29 import java.io.ObjectInputStream ; 30 import java.io.ObjectOutputStream ; 31 import java.net.ServerSocket ; 32 import java.net.Socket ; 33 import java.net.SocketException ; 34 import java.util.Random ; 35 36 public class TestSocketServer implements Runnable { 37 38 public TestSocketServer(int port) { 39 random = new Random (); 40 try { 41 this.ss = new ServerSocket (port); 42 } catch (IOException ioe) { 43 throw new JalistoException(ioe); 44 } 45 } 46 47 public void run() { 48 System.out.println("Run server"); 49 while (true) { 50 String socketInfos = null; 51 try { 52 socketInfos = connect(); 53 try { 54 while (true) { 55 Object message = readObject(); 56 System.out.println("\nread : " + message.toString() + "\n"); 57 sendReply(); 58 } 59 } catch (IOException ioe) { 60 if (ioe instanceof SocketException ) { 61 throw ioe; 62 } else { 63 System.out.println(ioe.getMessage()); 64 } 65 } catch (ClassNotFoundException cnfe) { 66 cnfe.printStackTrace(); 67 return; 68 } 69 } catch (SocketException se) { 70 if (se.getMessage().equals("Connection reset")) { 71 System.out.println("socket " + socketInfos + " closed"); 72 } else { 73 throw new RuntimeException (se); 74 } 75 } catch (IOException ioe) { 76 ioe.printStackTrace(); 77 return; 78 } 79 } 80 } 81 82 public void sendReply() throws IOException { 83 int delay = random.nextInt(900) + 100; 84 try { 85 Thread.sleep(delay); 86 } catch (InterruptedException e) { 87 } 88 toClient.writeObject("ok"); 89 toClient.flush(); 90 } 91 92 public String connect() throws IOException { 93 socket = ss.accept(); 94 System.out.println("Connect with " + socket.toString()); 95 fromClient = new ObjectInputStream (socket.getInputStream()); 96 toClient = new ObjectOutputStream (socket.getOutputStream()); 97 System.out.println("socket connected : " + socket.toString()); 98 return socket.toString(); 99 } 100 101 public Object readObject() throws IOException , ClassNotFoundException { 102 Object message = null; 103 while (message == null) { 104 message = fromClient.readObject(); 105 } 106 return message; 107 } 108 109 110 private ServerSocket ss; 111 private Socket socket; 112 private ObjectInputStream fromClient; 113 private ObjectOutputStream toClient; 114 115 private Random random; 116 117 public static void main(String [] args) { 118 TestSocketServer server = new TestSocketServer(6000); 119 server.run(); 120 } 121 } 122 | Popular Tags |