Implementing a layer 7 Protocol

Hi everybody
Ive learned Java for three years at school, but I am not really an expert
Im playing around with Java networking (a small client / server architecture) and now I want to implement a small protocol. The protocol should be modular and quite simple, but I don't know how to implement it.
My idea up to now was to write messageobjects which implement an interface and therefore contain a method called invokeAction. When any part receives such an object, the invokeAction Method is invoked. This means that the message contains all the logic needed to do something. But then it's difficult for the message to access Server / Client components and also the messages will become very big when the logic becomes more complex.
How can this be done in a more efficient way and how is such a protocol implemented in a real program
Sry for my bad english ;)

From what you describe, it sounds like you simply want to serialize an object using, for example, [ObjectOutputStream.writeObject()|http://java.sun.com/javase/6/docs/api/java/io/ObjectOutputStream.html#writeObject(java.lang.Object)].
You'll also have to serialize any other objects and primitives used by that method and not present on the other end.
As for efficiency, there's no point asking how to make it "more efficient" until you have specific performance requirements and specific problems where those requirements are not being met.

Similar Messages

  • How can I implement a new protocol over IP

    Hi,
    I want to implement a new protocol (my customized one) in solaris 8. This protocol will be something like UDP and will be using IP for communication.
    So how can i use IP stream module for that?
    thankx
    prasenjit

    I can give you some pointers regarding this. Although, I implemented protocol below IP.
    - Look for information on ipsecah and ipsecesp. These are pseudo devices on top of IP for Solaris 8.0.
    - Check how the protocol stack is built while booting.
    - If you intend to implement a module, rather than a driver then things might be little easy. You can push your module on top of IP. See man for "sad" and "autopush" mechanism
    - Sample drivers and modules from SUN are of great
    help. I came to know about the sample drivers very late.
    Otherwise, I would have saved some time.
    - Unix System V network programming by Rago is a very good reference.
    I hope this helps.
    -Ashutosh

  • Is it possibole to implement mutiple layer hierarchies in Essbase?

    Hi experts,
    I want to know whether the following layout is implemented. How to create different layer hierarchies in ESSBASE?
    If it does work , I want to drag this hierarchy into presentation. Please help me as soon as possible. Thanks.
    For example:
    Presentation Hierarchy
    Total
    ---Region(Region Table)
    -----District(Region Table)
    ---------Brand(Product Table)
    -------------Product Type(Product Table)
    -----------------Product Detail(Product Table)

    Well, I have to say that I do not really not OBIE so I can not make a good comparaison.
    What I could say is that in Essbase we use to have multiple dimension that we cross all the time
    Therefore in your exemple I would have 2 dimension, one called Entity :
    Total
    ----Location
    --------Region1
    ------------District1
    ------------District2
    --------Region2
    ------------District3
    ------------District4
    An other called Product:
    -Product
    -----Brand
    ---------Product Type
    -------------Product 1
    Then you "cross" the two dimension like:
    Product Type
    Product1 | Product 2 | Prodcut 3 ...
    Distric1 100 200 300
    Distric2 110 220 250
    There is on exemple here of hierarchy done in Outline Editor in Essbase:
    http://2.bp.blogspot.com/__2AaArK5lW8/TUWdz2-HQbI/AAAAAAAACzc/pp7vUsTRhmQ/s1600/1.png
    One exemple of the result in essbase:
    http://3.bp.blogspot.com/-9yQ4tsNOd-s/TWhGeHjK53I/AAAAAAAAAXw/B4lU72dEUPg/s1600/AddinMode.jpg
    Hope it will help you
    PS: Could you mark my answer as helpfull :)

  • JMS implementation of P2P protocol: need for statefulness!

    Hello!
    I have to implement the Chord peer-to-peer protocol using JMS. I'm thinking of using a message-driven bean per node in order to manage asynchronous communication (and I've been able to make this work).
    The problem is that the protocol requires that every node keep some information about its neighbours, about the data it manages, etc.
    This means I have to keep a state of the node, which doesn't seem to be possible if I use EJBs.
    I think that a possible solution might be to couple the message-driven JMS bean with a session bean, and instruct the message-driven been to forward to the session bean the messages it receives. This should allow the session bean to manage the state of the node, while leaving the communication stuff to the message-driven bean.
    My doubts are:
    - How can the message-driven bean find and contact the associated session bean?
    - Is this design practical?
    Thank you!

    You are accessing the runtime mbean of a JMS destination. The JNID name of a destination is not available on the runtime destination MBean.
    If you are using jms-system-resource to deploy your JMS module, you should be able to access the deployment mbean of the destination. The starting MBean for JMS is JMSSystemResourceMBean in this case.

  • Java implementation of rsync protocoll

    Hi,
    has anyone heard of a java implementation of the rsync protokoll other than the inactive "JarSync" Project on SourceForge?
    Or is there anything that compares to rsync that has been implemented in java?
    --- carco

    check out this site www.sourceforge.net. There are a lot of free , opensource projects available for download. Try and search there. I am sure you'll get one.

  • New protocol implementation

    Hello
    I implemented my own Protocol class for sip, I used the following package name com.sun.midp.io.j2me.sip.
    I made this Protocol class inherit the ConnectionBaseInterface.
    I put this file with the rest of the jsr180 implementation classes in a jar named nist-siplite.jar.
    I created a MIDlet to test my Protocol class and when I tried to open the connection with Connector.open("sip:..."),
    I got the following exception :
    Uncaught exception java/lang/NoClassDefFoundError: com/sun/midp/io/j2me/sip/Protocol: Cannot create class in system package .
    My command to run the MIDlet is the following :
    ${wtk}/bin/emulator -classpath ${wtk}/lib/nist-siplite.jar;build/bin/ShootLite.jar -Dmicroedition.platform=j2me -Xdescriptor:build/bin/ShootLite.jad
    where ${wtk} is my wtk_home.
    I'm using the DefaultColorPhone to run my MIDlet.
    javax.microedition.io.Connector.protocolpath=com.sun.midp.io
    Now if I put the Protocol class in another package, by example, gov.nist.microedition.io.j2me.sip and change the
    javax.microedition.io.Connector.protocolpath attribute in the system.config to gov.nist.microedition.io
    I got he following exception :
    [exec] java.lang.ClassNotFoundException: com/sun/midp/io/j2me/sip/Protocol
    [exec] at javax.microedition.io.Connector.openPrim(+99)
    [exec] at javax.microedition.io.Connector.open(+15)
    [exec] at javax.microedition.io.Connector.open(+6)
    [exec] at javax.microedition.io.Connector.open(+5)
    [exec] at examples.jsr180.Shootme.<init>(+53)
    [exec] at java.lang.Class.runCustomCode(+0)
    [exec] at com.sun.midp.midlet.MIDletState.createMIDlet(+19)
    [exec] at com.sun.midp.midlet.Selector.run(+22)
    [exec] java.lang.ClassNotFoundException: com/sun/midp/io/j2me/sip/Protocol
    [exec] at javax.microedition.io.Connector.openPrim(+99)
    [exec] at javax.microedition.io.Connector.open(+40)
    [exec] at javax.microedition.io.Connector.open(+6)
    [exec] at javax.microedition.io.Connector.open(+5)
    [exec] at examples.jsr180.Shootme.<init>(+53)
    [exec] at java.lang.Class.runCustomCode(+0)
    [exec] at com.sun.midp.midlet.MIDletState.createMIDlet(+19)
    [exec] at com.sun.midp.midlet.Selector.run(+22)
    [exec] javax.microedition.io.ConnectionNotFoundException: The requested pro
    tocol does not exist sip://5060
    [exec] at javax.microedition.io.Connector.open(+72)
    [exec] at javax.microedition.io.Connector.open(+6)
    [exec] at javax.microedition.io.Connector.open(+5)
    [exec] at examples.jsr180.Shootme.<init>(+53)
    [exec] at java.lang.Class.runCustomCode(+0)
    [exec] at com.sun.midp.midlet.MIDletState.createMIDlet(+19)
    [exec] at com.sun.midp.midlet.Selector.run(+22)
    I know for sure that the system.config's attributes are well read because I print them from the MIDlet application and they're right
    But the wireless toolkit seems to continue to look for the class in the com.sun.midp.io.j2me.sip package.
    So I'd like to know if you've already encountered this kind of problem or have any ideas about this....?
    Thanks in advance for your reply.
    Best regards.

    Ok, it seems that the wireless toolkit doesn't allow one to load a class whose the package name is one of the system (i.e. com.sun.midp.io). The remaining question is how to force the wireless toolkit to correctly use
    the protocol path defined in the system.config file...(i.e. javax.microedition.io.Connector.protocolpath=gov.nist.micoredition.io).
    I'm wondering if the wireless toolkit doesn't take this protocolpath because the others protocol doesn't exist anymore.
    Hope that someone can answer this question.
    Best regards

  • Implementing Network Protocol (Sockets)

    Hi, I'm having a hard time to implement a network protocol on my project.
    I'm doing a socket program that pass iso8583 message to the server. But one of the requirements is a network protocol which is the length of the message that is 4 bytes.
    Here's my code.
    public static void StartClient()
    // Data buffer for incoming data.
    byte[] bytes = new byte[1024];
    // Connect to a remote device.
    try
    // Establish the remote endpoint for the socket.
    // This example uses port 11000 on the local computer.
    IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("192.168.206.135"), 6004);
    // Create a TCP/IP socket.
    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    // Connect the socket to the remote endpoint. Catch any errors.
    try
    if (!sender.Connected)
    sender.Connect(remoteEP);
    string data = new Client().Test();
    int len = data.Length;
    byte[] msg = Encoding.ASCII.GetBytes(len.ToString());
    int bytesSent = sender.Send(msg,SocketFlags.None);
    //// Receive the response from the remote device.
    int bytesRec = sender.Receive(bytes);
    Console.WriteLine("Received = {0}",
    Encoding.ASCII.GetString(bytes, 0, bytesRec));
    sender.Shutdown(SocketShutdown.Both);
    sender.Close();
    catch (ArgumentNullException ane)
    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
    catch (SocketException se)
    Console.WriteLine("SocketException : {0}", se.ToString());
    catch (Exception e)
    Console.WriteLine("Unexpected exception : {0}", e.ToString());
    catch (Exception e)
    Console.WriteLine(e.ToString());
    Console.ReadLine();
    Can someone help me with this and kindly check if my code is ok?

    this is only for parsing and building ISO8583. i need to know how to append header details of the message that i will pass on the server. thanks btw

  • Modbus protocol implementa​tion

    Hello colleagues,
    I need to use a PC with a LabVIEW application to serve as modbus master to talk to a single modbus slave that concentrates data from another modbus, where it is the master talking to around 30 instruments (slaves). I have no experience with implementing modbus protocol, and have downloaded the NI Modbus Toolkit. Does someone have experience with using this toolkit - there is no help/manual, and I'd appreciate an example diagram(s) showing me the typical implementation of the protocol (initiating modbus session, sending commands, reading data, ...).
    Thanks in advance,

    See this thread for the protocol manual.
    http://forums.ni.com/ni/board/message?board.id=170&message.id=197677&query.id=96682#M197677
    Attached is a serial query.
    Attachments:
    my modbus serial query.llb ‏518 KB

  • Protocol Independent Servlets

    Hello All,
    It is a known fact that the Servlet API is protocol independent and Additional classes like HttpServlet provide facility to use HTTP protocol for communication.
    I was just wondering, how to use the protocol independent feature of the Servlet API and use it for my own protocol. Is there any other pratical and simple example where Servlets are used with other protocols other than HTTP. I am really interested to have a look at it.
    Thanks in advance!
    Regards,
    Giridhar Manepalli

    Disregard my earler email :-) I somehow managed to
    forget few words!
    Thanks Steve!
    Even before implementing classes which extend
    ServletRequestWrapper etc, we need to have certain
    protocol specific methods implemented by the web
    container.No. The container only cares abuot the general request-response theme. There is the one exception of the HTTP protol. Since the HTTP protocol is the most often used, interfaces for that protocol are defined as part of the J2EE spec (HttpServlet, HttpServletRequest, HttpServletResponse, HttpSession) and implementations provided by the container to fullfill the spec (HttpServlet is a class, no implementation needed. Tomcat uses CoyoteRequest and CoyoteResponse to implement the HttpServletReuest and HttpServletResponse interfaces).
    You would be responsible for any protocol except HTTP. But the idea is to follow the same format.
    1) Extend GenericServlet to ProtocolServlet.
    2) Extend ServletRequest and ServletResponse to ProtocolServletRequest and ProtocolServletResponse
    3) Create implementations of the ProtocolServletRequest and ProtocolServletResponse.
    -- Best bet is to extend ServletRequestWrapper and ServletResponseWrapper for these classes, since they will need to wrap around the original ServletRequest/ServletResponse.
    -- You can follow the basic model provided by the HTTP implementation and never show the name of the implementing classes, just the interfaces ProtocolServletRequest and ProtocolServletResponse
    4) Use the ProtocolServlet to read the ServletRequest's input stream and
    -- Generate a ProtocolServletRequest and ProtocolServletResponse out of the ServletRequest and ServletResponse provided (along with pertinent information from the request's input stream).
    -- Determine the best course of action based on the contents of the input stream
    -- Dispatch the ProtocolServletRequest and ProtocolServletResponse to an appropriate method.
    I was going through the code of tomcat, I came to
    know that CoyoteRequest class which implements
    HttpServletRequest, HttpServletResponse interfaces,
    is actually the one that is passed to the service
    method of the servlet as ServletRequest object.
    Now, CoyoteRequest as part of the container contract
    implemented HTTP Protocol specific code like "Method
    of HTTP Request viz., GET, POST etc" and some more
    protocol specific methods.
    I think, when J2EE specification says Servlets are
    protocol independent, it means that the containers
    can implement whatever protocols they want, thereby
    the application components deployed in the container
    can use that protocol services.It means that the Serlvet container CAN handle any protocol (in theory). The J2EE specs. require a non-specific servlet handling mechanism (GenericServlet, ServletRequest, and ServletResponse). It also requires the container to handle the HTTP protocol because that is the most likely to be used (and is required for JSP. So HttpServlet, HttpServletRequest, and HttpServletResponse, HttpSession).
    Servlets can still handle other protocols, but the container will not do it automatically. You will be forced to implement the details which sit on a layer above the generic handling.
    You may want to look around the web and see if there is a servlet implementation of the protocol you want to handle. I would be surprised if there is not an FTPServlet suite hanging around. Other protocols are less likely.
    If you do have to implement it yourself, make sure you read the specs on the protocl thoroughly. Your implementation will need to flawlessly parse incoming requests and send out responses in a well formed protocol-dependent manner.
    >
    Any thoughts?
    Regards,
    Giridhar Manepalli

  • How to implement Modbus Ethernet communicat​ion in Lookout, if we want to simulate the PC as PLC ?

    Problem Description :
    Dear Sir,
    We are doing a project where we are using Lookout with
    Front end Modicon PLC. The communication is by
    Ethernet, using Modbus.
    Since the installation is at a distant place, we wanted
    to use another PC (running Lookout) to simulate the
    PLC. For this, we tried to communicate
    a: the server Lookout PC running Modbus Ethernet mode of
    Modbus object as Master
    b: with another PC (for simulating the PLC) running
    Modbus Slave
    We did not get any communication. (we have given the
    details of what we have done, at the end of this email)
    We also tried connecting the above 2 PC's as
    a: the server Lookout PC running Modbus Serial mode of
    Modbus object as Master
    b: with another PC (for simulating the PLC) running
    Modbus Slave object
    Again we did not get any communication.
    If instead of PC (b) we connect the Modbus simulator to
    PC (a), there is no problem in communicating
    Please let us know how to go about establishing the
    communication between 2 PC's using Modbus serial,
    and Modbus Ethernet. A detailed step by step procedure
    would help us a lot.
    Thanking you
    Warm Regards
    Raja Mahbubani
    Procedure of our trial with ethernet.
    This is what we have done in detail.
    On PC A:
    We created an object (Pot) and connected it to
    the modbus data member of the modbus object say 40001. In the
    properties of the modbus object we selected modbus ethernet mode
    of communication and in the IP address field we wrote the IP
    address of the machine B to which we are trying to communicate
    i.e. 152.63.50.2.
    On PC B: we tried the following two methods
    Trial 1 : We created a modbus slave object and
    inserted an expression for the same data memeber to which the
    object was connected hoping to get the value of the pot of machine
    A on machine B.
    Trial 2 : We created a modbus object on machine B and we wrote
    the IP address of machine A and inserted an expression for the
    same datamemeber to which the object was connected hoping to get
    the value of the pot of machine A on machine B.
    NI Software : Lookout
    Version : 4.0.1 or 4.5
    OS : Windows 98
    NI Hardware : N/A
    Drivers : N/A
    Other Hardware/Instruments : N/A
    CPU : Pentium
    RAM : 64
    Vendor : S-Tech
    Customer Information :
    Raja Mahbubani
    Theta Controls
    IN
    [email protected]
    Ph: (+91) 20 4222556/7

    The ModbusSlave which comes with Lookout currently supports only Serial communication. So, you cannot use Ethernet between your two PCs. At least not with Modbus Master-Slave setup (if you must speak Ethernet between the two PCs, IPASCII object lets you do that, but then you'll need to implement your own protocol).
    Since all you want to do is simulate a Modbus PLC on a PC, you can use the Serial mode of communication for now. And later on just modify the Object in your Server Lookout to use the Ethernet mode.
    For setting up a Serial Modbus Slave, use a null-modem cable between the two PCs (lines 2 and 3 are swapped). On your PC 'B,' create the Modbus Slave object with the right COM port for that PC. And on your PC 'A' create the regular Modbus Object as if you w
    ere connecting to the Modbus Simulator box. The only difference here is the cable. The simulator box uses a straight-through cable whereas the Slave needs a null-modem cable.
    Hope this helps.
    Rgds,
    Khalid

  • Help needed to start HTTP Protocol with timeout

    I am looking for information to point me in the right direction. I would like to create a class that would implement the HTTP protocol and would allow the user to specify a timeout if unable to connect to the server. I have used the URL and HttpURLConnection classes before, but have not used any of the other classes in the java.net package. I am just trying to create an app that will download a file from a specified URL. Something that I could use in the future and something to get more programming experience using the java.net package.
    Could you tell me:
    1) Which classes I would need to use to help implement a timeout
    2) Where I can find an example or other information on how to implement the HTTP protocol with the class from question 1 above.
    TIA for any information

    That would definately reduce the coding time but would
    do little to help with my understanding of classes in
    the java.net package or to gather a better
    understanding of the HTTP protocol. :-)
    That said, I am currently downloading the 1.5 beta to
    see what they have done.If it's just an academic thing to re-invent the wheel (code) that deals with the HTTP protocol, then go right ahead (ok, you don't need my permission).

  • Leave Request two layer approval

    Dear Experts,
    I'm trying to implement two layer approval leave request workflow by copying and modifying standard workflow WS12300111.
    I follow the guide from this link:
    http://wiki.sdn.sap.com/wiki/display/ERPHCM/CustomizingtheESSLeaveApprovalusingBusiness+Workflow
    My workflow step is as follow:
    1. first approver has approve the request
    2. reset req object status to SENT
    3. set next approver using method if_pt_req_request->set_next_processor
    4. send the request to the second approver
    I have implement badi PT_GEN_REQ to set first approver (method IF_EX_PT_GEN_REQ~FIND_RESP_AND_DEFAULT_NEXT_PRC) so that the first approver name shown correctly when requestor create the request.
    Now there are 3 problems I'm facing:
    1. After the FIRST approver approve the request, the note he input is shown twice. I found out this is because the status change create new version of the document. I have tried to clear this note when changing the status using method if_pt_req_request->set_notice. However, the method ignore if the notice is set to blank. Is there anyway to hadle this?
    2. When SECOND approver reject the request, I want the request to be revised by the requestor, and then forwared to FIRST approver after that. For this purpose, before send the workitem to requestor back, I put step to set approver back to FIRST approver again using method if_pt_req_request->set_next_processor. But it seems this doesn't work and the request is sent to SECOND approver after revised. The supervisor name that is shown when requestor revise the request also show the SECOND approver name instead the FIRST approver.
    3. I find difficulties to create email notification if the request is changed by the requestor during approval process, since there are no event triggered. Is there anyway to trigger this event or is there any workaround?
    Thank you.
    Regards,
    Ponty

    Hi Ponty,
    I am trying to implement two layer approval for leave request, too.
    I took a copy of standard WS12300111 as you did.
    I followed the guide, you mentioned. For one level approval this works nearly out of the box.
    But I don't understand the second half of the guide.
    For me it will be the first time to implement a BAdI. I never did this before.
    Can you please explain me, how to do it and how you enhanced the workflow for two layer approval?
    Some screenshots might be useful. Eventually you can enhance the guide you mentioned.
    Regarding the numerous questions on multi level approval, these hints might be useful for a large number of users.
    I would be very happy, If somebody can help me, becaus I didn't know any workflow experts who can help me implementing the BAdI.
    Thank you.

  • How to improve custom protocol speed?

    Hi
    I used RMI to get an array of shorts from server.
    Then I thought that using RMI for transferring arrays of primitives
    is not a good idea, that is why I decided to create my own protocol for
    transferring data.
    The other goal to implement my own protocol was to show a data
    transferring progress to user.
    I thought it was not easy to do it with RMI If I am wrong let me know
    how to do it with RMI please :)
    Unfortunately my protocol implementation works slower than RMI.
    Here goes code for simplified version of my protocol.
    Can anyone suggest what I should do to make it work faster.
    Protocol is designed to transfer data provided by FooData from
    FooDTPServer to every connected FooDTPClient.
    The protocol works as follows:
    FooDTPClient connects to FooDTPServer and sends code that indicates
    that it is a client(all codes are described at DTPCodes).
    Server replies with code that indicate that it is FooDTPServer.
    Client asks server for data.
    Server sends a length of data it is going to send and then sends the
    data.
    If client wants more data it sends new request for data.
    If it wants to close connection, it sends special code.
    If client sends wrong code at any state of conversation with server
    the server closes connection.
    Here goes implementation of protocol.
    // file DTPCodes.java
    public class DTPCodes {
    * client sends it to server to at the begin of conversation.
    public static final byte HELLO_IM_DTP_CLIENT = 1;
    * server sends this code as a replay to client
    * HELLO_IM_DTP_CLIENT code.
    public static final byte HELLO_IM_DTP_SERVER = 2;
    * client request for data must start with this code.
    public static final byte GIVE_ME_DATA = 3;
    * client sends this message when he goes away.
    public static final byte BYE = 5;
    // file FooData.java
    /**Simple data provider */
    public class FooData {
    /** Data that FooDTPServer sends to client */
    public static final short[] DATA = new short[1024*768];
    // file FooDTPServer.java
    import java.io.*;
    import java.net.*;
    import java.util.*;
    /**FooDTPServer is a simple multithreaded server that sends data */
    public class FooDTPServer {
    public static final int DEFAULT_PORT = 4567;
    /**Contains all running DTPServerThreades*/
    private Set serverThreadsSet = new HashSet();
    /**this flag indicates is server listening or not */
    private boolean listening = false;
    /**port on wich server will accept connection*/
    private int port;
    * Creates instance of FooDTPServer that will run on given port
    * @param port - port on which you what server to listen
    public FooDTPServer(int port) {
    this.port = port;
    * starts server
    * @throws IOException
    * @throws IllegalStateException if server is already running
    public void start() throws IOException, IllegalStateException,
    IllegalArgumentException {
    if (listening == true)
    throw new IllegalStateException("Server already running");
    ServerSocket serverSocket = new ServerSocket(port);
    listening = true;
    while (listening) {
    DTPServerThread t = new
    DTPServerThread(serverSocket.accept());
    t.start();
    serverThreadsSet.add(t);
    serverSocket.close();
    * Stops server
    public void stop() {
    listening = false;
    serverThreadsSet.iterator();
    Iterator iter = serverThreadsSet.iterator();
    while (iter.hasNext()) {
    DTPServerThread t = (DTPServerThread) iter.next();
    if (t.isServing()) {
    t.stopServing();
    * Starts server on default port
    public static void main(String[] args) throws Exception {
    System.out.print("Starting server on port " + DEFAULT_PORT +
    "... \t");
    FooDTPServer fooDTPServer = new FooDTPServer(DEFAULT_PORT);
    System.out.println("Server has started.");
    fooDTPServer.start();
    /** Thead that represent connection with paricular client reqest
    private class DTPServerThread extends Thread {
    /**This flags thread to continue running. */
    private boolean continueServing;
    /**Socket with client */
    private Socket socket;
    /** Creates instance of DTPServerThread.
    * @param socket - socket with client
    * @throws IllegalArgumentException
    public DTPServerThread(Socket socket) throws
    IllegalArgumentException {
    this.socket = socket;
    continueServing = true;
    /**Stops this thread*/
    public void stopServing() throws IllegalStateException {
    if (!continueServing)
    throw new IllegalStateException("Server already
    stoped");
    continueServing = false;
    * @return true if thread is running
    public boolean isServing() {
    return continueServing;
    public void run() {
    try {
    BufferedOutputStream bos = new
    BufferedOutputStream(socket.
    getOutputStream(), 1024 * 768);
    DataOutputStream dos = new DataOutputStream(bos);
    BufferedInputStream bis = new
    BufferedInputStream(socket.
    getInputStream());
    DataInputStream dis = new DataInputStream(bis);
    //check if this is FooDTPClient connected
    if (dis.readByte() == DTPCodes.HELLO_IM_DTP_CLIENT) {
    //write respone to indicate that this is
    FooDTPServer
    dos.writeByte(DTPCodes.HELLO_IM_DTP_SERVER);
    dos.flush();
    while (continueServing) {
    //if cliens requests data
    if (dis.readByte() == DTPCodes.GIVE_ME_DATA) {
    short[] data = FooData.DATA;
    //send him the abount of data you are
    going to send
    dos.writeInt(data.length);
    // then send data
    for (int i = 0; i < data.length; i++) {
    dos.writeShort(data);
    dos.flush();
    else {
    //if client doesn't want more data
    break;
    dos.flush();
    dos.close();
    bos.close();
    bis.close();
    dis.close();
    socket.close();
    catch (IOException ioex) {
    ioex.printStackTrace();
    continueServing = false;
    serverThreadsSet.remove(this);
    //file FooDTPClient.java
    import java.io.*;
    import java.net.*;
    /**Instances of this class interracte with server*/
    public class FooDTPClient {
    private boolean connected = false;
    /**Socket with server */
    private Socket socket;
    private BufferedInputStream bis;
    private DataInputStream dis;
    private BufferedOutputStream bos;
    private DataOutputStream dos;
    private String serverAddress;
    private int port;
    * Creates instance with specified server address and port
    * @param serverAddress - server address
    * @param port - server port;
    * @throws IllegalArgumentException if serverAddress==null or port
    <=0
    public FooDTPClient(String serverAddress, int port) throws
    IllegalArgumentException {
    if (serverAddress == null)
    throw new IllegalArgumentException("serverAddress is
    null");
    this.serverAddress = serverAddress;
    if (port <= 0)
    throw new IllegalArgumentException("port = " + port + " <=
    0");
    this.port = port;
    public void connect() throws IOException, IllegalStateException {
    if (connected)
    throw new IllegalStateException(
    "This instance of DTPClient already connected to
    server.");
    socket = new Socket(serverAddress, port);
    bis = new BufferedInputStream(socket.getInputStream(),
    1024*768);
    dis = new DataInputStream(bis);
    bos = new BufferedOutputStream(socket.getOutputStream());
    dos = new DataOutputStream(bos);
    dos.writeByte(DTPCodes.HELLO_IM_DTP_CLIENT);
    dos.flush();
    byte serverReply = dis.readByte();
    if (serverReply != DTPCodes.HELLO_IM_DTP_SERVER) {
    throw new IllegalStateException("Server gave wrong
    reply");
    connected = true;
    public synchronized short[] getData() throws IOException,
    IllegalStateException {
    if (!connected) {
    throw new IllegalStateException(
    "DTPClient not connected to server");
    dos.writeByte(DTPCodes.GIVE_ME_DATA);
    dos.flush();
    short[] data = new short[dis.readInt()];
    for (int i = 0; i < data.length; i++) {
    data = dis.readShort();
    return data;
    public synchronized void closeConnection() throws
    IllegalStateException,
    IOException {
    if (!connected) {
    throw new IllegalStateException(
    "DTPClient is not connected to server");
    dos.writeByte(DTPCodes.BYE);
    dos.flush();
    dos.close();
    bis.close();
    dis.close();
    bis.close();
    if (socket.isConnected()) {
    socket.close();
    connected = false;
    public synchronized boolean isConnected() {
    return connected;
    public static void main(String[] args) throws Exception {
    int numberOfTries = 100;
    long totalTime = 0;
    FooDTPClient fooDTPClient = new FooDTPClient("localhost",
    FooDTPServer.DEFAULT_PORT);
    fooDTPClient.connect();
    for (int i = 0; i < numberOfTries; i++) {
    long beginTime = System.currentTimeMillis();
    short[] sa = fooDTPClient.getData();
    long operationTime = System.currentTimeMillis() -
    beginTime;
    totalTime += operationTime;
    // System.out.println("Operation N" + i + " took\t" +
    operationTime);
    fooDTPClient.closeConnection();
    System.out.println("Average test time is\t" +
    (totalTime / numberOfTries));
    And here goes server and client that transfer data over RMI
    //file FooRemote.java
    import java.rmi.*;
    public interface FooRemote extends Remote {
    public short[] getData() throws RemoteException;
    //file FooRemoteImpl.java
    import java.rmi.*;
    public class FooRemoteImpl implements FooRemote{
    public short[] getData() throws RemoteException{
    return FooData.DATA;
    //file FooRMIServerRunner.java
    import java.rmi.server.*;
    import java.rmi.*;
    public class FooRMIServerRunner {
    public static void main(String[] args)throws Exception {
    java.rmi.registry.LocateRegistry.createRegistry(5000);
    FooRemoteImpl fooRemote = new FooRemoteImpl();
    RemoteStub fooRemoteStub =
    UnicastRemoteObject.exportObject(fooRemote);
    Naming.bind("rmi://localhost:5000/FooService", fooRemoteStub);
    // file FooRMIClient.java
    import java.rmi.*;
    import java.net.*;
    public class FooRMIClient {
    FooRemote fooRemote;
    public FooRMIClient() throws RemoteException,
    MalformedURLException,
    NotBoundException {
    fooRemote = (FooRemote) Naming.lookup(
    "rmi://localhost:5000/FooService");
    public short[] getData()throws RemoteException{
    return fooRemote.getData();
    public static void main(String[] args)throws Exception {
    int numberOfTries = 100;
    long totalTime = 0;
    FooRMIClient fooRMIClient = new FooRMIClient();
    for (int i = 0; i < numberOfTries; i++) {
    long beginTime = System.currentTimeMillis();
    short[] sa = fooRMIClient.getData();
    long operationTime = System.currentTimeMillis()-beginTime;
    totalTime+=operationTime;
    // System.out.println("Operation N"+i+" took\t" +
    operationTime);
    System.out.println("Average test time is\t" +(totalTime /
    numberOfTries));
    Any help is appreciated.
    Best regards,
    Vitaliy.

    A lot to quote up there, but as for moving away from RMI, since you have the code and in my personal estimation there's really not THAT much overhead for non-remote return types, is there a reason you wish NOT to stay with RMI for this if you have that ability?
    I would however suggest also GZIPping the short[] array and other data as that will save on xfer time, either in RMI or your own personal protocol.

  • Transport Protocol

    Hello all,
    I am implementing a transport protocol that sends data from one source to another over multiple paths. The protocol is to work as follows:
    When the protocol receives data, the data will be fragmented into TCP segments. Then TCP connections will be opened in the available paths to the destination and each segment will be
    transmitted in one of the connections. The TCP connections are independent of each other.
    Before the protocol can open TCP connections to the destination, it has to know the available paths provided by the network to the destination. This is where I have problems. Do you have any
    idea how I can get this information? Also the destination has to know the path of each packet for retransmission purposes in case the packet gets lost.
    Any help is appreciated.
    Thanks
    Mpho

    Ummmm... if you're doing this with Sockets, the TCP/IP protocol stack does all of this work for you...
    I think I haven't understood you question, sorry.

  • Implementing copyWithZone:

    Quick question about implementing copyWithZone: (NSCopying protocol) in a class. Should the copyWithZone: method be responsible for (auto)releasing the copied object? i.e.
    <pre>
    -(id)copyWithZone:(NSZone *)zone
    MyClass *copy=[[[MyClass alloc] init] autorelease];
    return copy;
    </pre>
    The Apple developer documentation for copyWithZone: doesn't have the method autorelease the copy, but the documentation states elsewhere that the object responsible for alloc/init'ing an object should be responsible for releasing it. Is there a reason that the copyWithZone: method shouldn't autorelease the copy?
    Thanks,
    Jim
    iMac G4, PowerBook G4    

    That's pretty much the idea. Of course, you mostly need to return a copy from a method like your example when you don't want the original object (that you send the message to) modified. Your use of the term "value" is a little confusing in the example just above. I would concoct an example of an instance method for returning a copy of the object to which the message is sent, rather than a copy of one of its instance variables.
    Your example seems to be about an object that you want to make a copy of, and then auto-release as expected of an object returned from a method whose name is not copy or alloc. But yes, you should definitely return an autoreleased copy of such an object if you don't want the user of the class to modify the original. Is that clear as mud? I'm almost starting to confuse myself!

Maybe you are looking for

  • How do you delete photos in photo stream?

    How can I delete photos on my photo stream? My daughter added a monster photo that I would like off my phone and iPad. I know how to turn off photo stream i want to delete a photo. Thank you.

  • Apple tv 3 Vimeo search

    I just bought an apple tv v3 and am not able to find videos on Vimeo using the search. I see many posts regarding the problem but no solutions. Any new info? Thanks, Curt

  • Improper change to clamshell mode

    MBA, no bluetooth devices, on Wifi, no external keyboard or mouse. External monitor connected through Thunderbolt. USB devices: external hard drive, NeatWorks scanner. Behavior: when the lid is closed the MBA switches to clamshell mode (external moni

  • ITunes 8.0.1 available

    Downloading at the moment.

  • I never received my deposit refund of $250

    I was told that my refund would be returned after a year of subscription as long as I have no late payments. I made the deposit on oct 12 last year and I have no late payments. I called the financial services a few days before oct 12 of this year and